问题描述:
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.
示例:
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
问题分析:
对以此类问题,我们可以转换为一个图遍历的问题(BFS),图的每个节点间只有同一个位置上的字母不相同。设置visited标志数组,记录访问过的节点。wordList中包含了所有可以利用的节点。
过程详见代码:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> visited;
unordered_set<string> wordSet(wordList.begin(), wordList.end());
int level = 1;
int lastNum = 1;
int curNum = 0;
queue<string> que;
que.push(beginWord);
visited.insert(beginWord);
while (!que.empty())
{
string cur = que.front();
que.pop();
lastNum--;
for (int i = 0; i < cur.length(); i++)
{
for (char c = 'a'; c <= 'z'; c++)
{
if (c != cur[i])
{
string tcur = cur;
tcur[i] = c;
if (endWord == tcur && wordSet.find(tcur) != wordSet.end())
return level + 1;
if (wordSet.find(tcur) != wordSet.end() && visited.find(tcur) == visited.end())
{
curNum++;
visited.insert(tcur);
que.push(tcur);
}
}
}
}
if (lastNum == 0)
{
lastNum = curNum;
curNum = 0;
level++;
}
}
return 0;
}
};