[LeetCode 127] Word Ladder
3964 ワード
https://leetcode.com/problems/word-ladder/
http://www.lintcode.com/zh-cn/problem/word-ladder/
2つの単語(startとend)と辞書を与えて、startからendへの最短変換シーケンスを見つけます.
例:は毎回1文字しか変更できません. 変換中の中間単語は辞書に表示されなければならない.
サンプル
次のようなデータが表示されます.
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
最も短い変換シーケンスは「hit」->「hot」->「dot」->「dog」->「cog」です.
長さ5を返します
に注意変換シーケンスがない場合は0を返します. すべての単語は同じ長さを有する. すべての単語には小文字しか含まれていません.
http://www.lintcode.com/zh-cn/problem/word-ladder/
2つの単語(startとend)と辞書を与えて、startからendへの最短変換シーケンスを見つけます.
例:
サンプル
次のようなデータが表示されます.
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
最も短い変換シーケンスは「hit」->「hot」->「dot」->「dog」->「cog」です.
長さ5を返します
に注意
// ---------------------------
// BFS non-recursive method
// ---------------------------
//
// Using BFS instead of DFS is becasue the solution need the shortest transformation path.
//
// So, we can change every char in the word one by one, until find all possible transformation.
//
// Keep this iteration, we will find the shorest path.
//
// For example:
//
// start = "hit"
// end = "cog"
// dict = ["hot","dot","dog","lot","log","dit","hig", "dig"]
//
// +-----+
// +-------------+ hit +--------------+
// | +--+--+ |
// | | |
// +--v--+ +--v--+ +--v--+
// | dit | +-----+ hot +---+ | hig |
// +--+--+ | +-----+ | +--+--+
// | | | |
// | +--v--+ +--v--+ +--v--+
// +----> dot | | lot | | dig |
// +--+--+ +--+--+ +--+--+
// | | |
// +--v--+ +--v--+ |
// +----> dog | | log | |
// | +--+--+ +--+--+ |
// | | | |
// | | +--v--+ | |
// | +--->| cog |<-- + |
// | +-----+ |
// | |
// | |
// +----------------------------------+
//
// 1) queue <== "hit"
// 2) queue <== "dit", "hot", "hig"
// 3) queue <== "dot", "lot", "dig"
// 4) queue <== "dog", "log"
//
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
unordered_map<string, int> dis;
dis.insert(make_pair(beginWord, 1));
queue<string> q;
q.push(beginWord);
while (!q.empty()) {
string word = q.front();
q.pop();
if (word == endWord) {
break;
}
for (int i = 0; i < word.size(); i++) {
string tmp = word;
for (char c = 'a'; c <= 'z'; c++) {
tmp[i] = c;
if (wordDict.count(tmp) == 1 && dis.count(tmp) == 0) {
q.push(tmp);
dis.insert(make_pair(tmp, dis[word] + 1));
}
}
}
}
if (dis.count(endWord) == 0) {
return 0;
} else {
return dis[endWord];
}
}
};