您的位置:首页 > 其它

*Leetcode 127. Word Ladder

2018-01-08 23:09 387 查看
https://leetcode.com/problems/word-ladder/description/

搜索题,练习数据结构和估算时间了。我的做法,构建图,然后BFS。据说从end找begin会快一点。

struct Node {
int word_id;
int pre;
int depth;
Node(int wi, int pre, int d):word_id(wi), pre(pre), depth(d){} ;
};

class Solution {
public:

bool canConverse(string s1, string s2) {
int cnt = 0;
if (s1.size() != s2.size()) return 0;
for (int i = 0; i < s1.size(); i++) {
if (s1[i] != s2[i]) cnt ++;
if (cnt > 1) break;
}
return cnt == 1;
}

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if (beginWord == endWord) return 0;
if ( beginWord != endWord && wordList.size() == 0 ) return 0;
if (find(wordList.begin(), wordList.end(), endWord) == wordList.end()) return 0;
int begin_idx = wordList.size();
wordList.push_back(beginWord);
int end_idx = find(wordList.begin(), wordList.end(), endWord) - wordList.begin();

set< pair<int, int> > visit;
set< pair<int, int> > canreach;
unordered_map <int, vector<int> > link;

unordered_map<string, int>word2idx;
for (int i = 0; i < wordList.size(); i++) {
word2idx[wordList[i]] = i;
}

for (int i = 0; i < wordList.size()-1; i++) {
for (int j = i + 1; j < wordList.size(); j++) {
if (canConverse(wordList[i], wordList[j])) {
if (link.find( word2idx[ wordList[i] ] ) == link.end()) {
link[ word2idx[ wordList[i] ] ] = vector<int>();

}

if (link.find( word2idx[ wordList[j] ] ) == link.end()) {
link[ word2idx[ wordList[j] ] ] = vector<int>();
}

link[ word2idx[ wordList[i] ] ].push_back( word2idx[ wordList[j] ] );
link[ word2idx[ wordList[j] ] ].push_back( word2idx[ wordList[i] ] );
}

}
}

queue < Node > q;
q.push( Node(end_idx, -1, 1) );
while (!q.empty()) {
Node tp = q.front();
if (tp.word_id == begin_idx) return tp.depth;
q.pop();
if (tp.depth > wordList.size() + 1) continue;

vector <int> &check = link[ tp.word_id ];

for ( int i = 0; i < check.size(); i++ ) {
int to = check[i];
if (to == tp.word_id) continue;
if ( !visit.count( make_pair(tp.word_id, to) ) ) {
q.push( Node(to, tp.word_id, tp.depth+1) );
visit.insert( make_pair(tp.word_id, to) );
}
}
}

return 0;

}
};

貌似在这个数据上,更快的做法是,比如一个长为m的word,然后枚举m*26中可能,而不是像我这样预处理出来连接关系 https://leetcode.com/problems/word-ladder/discuss/40707/

难度不大,下次写的时候再按照这个思路写。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: