LeetCode 127. Word Ladder
题目
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.
For example,
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.
分析
这是一个深搜问题,我们从题目中可以知道:
求两单词之间的最短路径,并返回路径包含的单词数
无法找到路径时返回0
为了减少运算量,我采取了以下策略:
使用递归,每次递归只运算一步(即只进行一次单词到单词的转变)
使用当前的起始单词列表,把这个列表的单词可以“到达”的wordList中的所有单词组成一个新起始单词列表,并把新起始单词列表的单词从wordList中删去,轮数+1,进行下一次递归。
若起始单词列表中包含了endWord,则返回当前的轮数。
若新起始单词列表为空,且起始单词列表中没有endWord,返回0。
代码实现
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
vector<string> bW;
bW.push_back(beginWord);
return ladderLength_iterator(bW, endWord, wordList, 1);
}
private:
int ladderLength_iterator(vector<string>& beginWord, string& endWord, vector<string>& wordList,int num_round)
{
vector<string> bW;
while (!beginWord.empty())
{
string str = beginWord.back();
if (str == endWord)return num_round;
vector<string>::iterator it = wordList.begin();
while (it != wordList.end())
{
if (translate(str, *it))
{
bW.push_back(*it);
it = wordList.erase(it);
}
else it++;
}
beginWord.pop_back();
}
if (bW.empty())return 0;
return ladderLength_iterator(bW, endWord, wordList, (num_round + 1));
}
bool translate(string& a,string b)
{
int different = 0;
for (int index = 0; index < a.size(); index++)
{
if (a[index] != b[index])different++;
if (different == 2)return false;
}
return true;
}
};