思路:宽搜
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_set<string> visited;
queue<pair<string,int>> q;
q.push(make_pair(start, 1));
visited.insert(start);
while(!q.empty())
{
string curStr = q.front().first;
int curLen = q.front().second;
q.pop();
for(string::size_type i = 0; i < curStr.size(); ++i)
{
string tmp = curStr;
for(int j = 0; j < 26; ++j)
{
tmp[i] = j + 'a';
if(tmp == end) return curLen + 1;
if(dict.count(tmp) && !visited.count(tmp))
{
q.push(make_pair(tmp, curLen+1));
visited.insert(tmp);
}
}
}
}
return 0;
}
};
优化:直接把已经访问过的元素删除
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
queue<pair<string,int>> q;
q.push(make_pair(start, 1));
dict.erase(start);
while(!q.empty())
{
string curStr = q.front().first;
int curLen = q.front().second;
q.pop();
for(string::size_type i = 0; i < curStr.size(); ++i)
{
string tmp = curStr;
for(int j = 0; j < 26; ++j)
{
tmp[i] = j + 'a';
if(tmp == end) return curLen + 1;
if(dict.count(tmp))
{
q.push(make_pair(tmp, curLen+1));
dict.erase(tmp);
}
}
}
}
return 0;
}
};