用bfs搜索,替换start中每个字母,分别在字典中查找,找到就更新length,并将其推入队列
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
int shortest = INT_MAX;
dict.insert(end);
queue< pair< string, int> > q;
q.push( pair< string, int>( start, 1));
while( !q.empty()){
pair< string, int> cur = q.front();
q.pop();
if( cur.first == end){
shortest = shortest < cur.second ? shortest : cur.second;
continue;
}
string str = cur.first;
for( int i = 0; i < str.size(); ++i){
for( int j = 'a'; j <= 'z'; ++j){
if( str[i] == j)
continue;
string tmp = str;
tmp[i] = j;
if( dict.count(tmp)){
q.push( make_pair( tmp, cur.second+1));
dict.erase(tmp);
}
}
}
}
if( shortest == INT_MAX)
return 0;
return shortest;
}
};