class Solution {
public:
int ladderLength(string &start, string &end, unordered_set<string> &dict) {
//题目说起始词和结束词不一定在dict里,那么干脆把2个词都加进来
dict.insert(start);
dict.insert(end);
//len表示start与dict里其他每个单词之间的距离(转换长度);
//还可以表示是否被访问过:INT_MAX表示未被访问。
map<string, int>len;
for(auto w:dict) len[w] = INT_MAX;
len[start] = 0;
//先把start加入队列里。
queue<string>Q;
Q.push(start);
string cur; //cur保存每次队列里的首元素
while(!Q.empty()) // BFS
{
cur = Q.front();
Q.pop();
for(auto w:dict)
{ // 在dict里,寻找未被访问的cur的邻接点(与cur相差一个字符的单词)。
if(dif(cur, w)==1 && len[w]==INT_MAX)
{
//更新距离。这里和“单源最短路-无权图(边的权重是1)一样的思路”
len[w] = len[cur] +1;
Q.push(w);
}
}
}
// 如果图不连通,则无解返回0。
return len[end]==INT_MAX? 0: len[end]+1;
}
// 两个单词相差一个字符,可视作一对邻接点
int dif(string s1, string s2)
{
int d = 0, i;
for(i=0; i<s1.size(); i++)
{
if(s1[i]!=s2[i])
d++;
}
return d;
}
};