题目:
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Example:
beginWord = “hit”
endWord = “cog”
wordList = {“hot”,”dot”,”dog”,”lot”,”log”,”cog”}
一种转换顺序是:”hit” -> “hot” -> “dot” -> “dog” -> “cog”,
所以返回长度5
思路:
算单源最短路径,考虑用BFS和Dijkstra算法,由于Dijkstra算法是能用于计算正权图的,而这次题目中显然每个单词节点之间的权都为1,所以这道题使用BFS算法更为方便。
代码:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
queue<pair<string, int>> que;
que.push(make_pair(beginWord, 1));
set<string> wordlist;
for (int i = 0; i < wordList.size(); i++) {
wordlist.insert(wordList[i]);
}
while (!que.empty())
{
auto val = que.front();
que.pop();
for (int i = 0; i< val.first.size(); i++)
{
string str = val.first;//注意每一轮i循环都是下标跳到下一位。要重新给str赋值成原单词
for (int j = 0; j < 26; j++)
{
str[i] = 'a' + j;//每次修改一位,将这一位从a到z遍历,修改完后的单词保存在str
if (wordlist.find(str) != wordlist.end()) {
if (str == endWord) {
return val.second + 1;
}
que.push(make_pair(str, val.second + 1));
wordlist.erase(str);
}
}
}
}
return 0;
}
};