思路:
广度优先搜索;先构造一个字符串队列,并将start加入队列
1、对队列头字符串做每个字符替换
2、每次替换后,判断是否和end匹配,如果匹配返回答案
3、没有匹配,则在字典里面查询是否有邻近字符串
4、如果有,则将该字符串加入队列,同时将该字符串从字典里删除
5、重复1的过程,直到和end匹配。如果最后队列为空,但还未匹配到,则返回0
#include <iostream>
#include <sstream>
#include <string>
#include <queue>
#include <map>
#include <unordered_set>
using namespace std;
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
queue<string> Q;
Q.push(start);
int res = 1;
/*广度搜索*/
while (!Q.empty())
{
int n = Q.size();
while (n--) //层次遍历,使用层次遍历也可以求广度搜索的深度,在地图题目中使用数组保存每个位置的res值
{
string tmp = Q.front();
string last = tmp;
Q.pop();
/*探索所有可能*/
for (int i = 0; i < tmp.size(); i++)
{
tmp = last;
for (int j = 0; j < 26; j++)
{
tmp[i] = 'a' + j;
if (tmp == end) //找到答案,退出
return res + 1;
if (dict.find(tmp) != dict.end())
{
Q.push(tmp);
dict.erase(tmp); //从字典中删除该字符串
}
}
}
}
res++;
}
return 0;
}
};
int main()
{
unordered_set<string> dict;
dict.insert("hot");
dict.insert("dot");
dict.insert("dog");
dict.insert("lot");
dict.insert("log");
Solution S;
string start = "hit";
string end = "cog";
cout <<S.ladderLength(start, end, dict) << endl;
system("pause");
return 0;
}