一次只允许变动一个字符,然后得到目标字符串最少步数.
我们把每个合法字符看成一个点,之间的变化看成边,那么就是个图,就是球start到end的最短路.
用BFS就可以了...
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 if(start == end) return 1; queue<string > que; map<string , int> dist; dist[start] = 0; que.push(start); while(!que.empty()){ string top = que.front();que.pop(); for(int i = 0 ; i < top.length() ; i++){ for(int j = 'a' ; j <= 'z' ; j++){ if(j != top[i]){ string next = top; next[i] = j; if(next == end){ return dist[top] + 2; } if(dict.find(next) != dict.end() && dist.find(next) == dist.end()){ dist[next] = dist[top] + 1; que.push(next); } } } } } return 0; } };