This question is not difficult. The essence is BFS. Starting from a word, his next layer can be changed step by step and never changed to those strings. The question is, how can we determine the strings that can be changed? There are two conditions: one, which can only be obtained by changing a number from the string on the previous layer, and the other, after which the word must be in the dictionary. Note that it is possible to change a letter, rather than the editing distance is 1, or it is complicated. There are many more situations.
My initial thought was to create a map to save all the words that can change from the start word to those that can change in one step. Too young too simple, which times out in a very dictionary test case. Why does it Time out? When the dictionary is very large, everyone can change to each other. It is very costly to generate a dictionary after my ing, because each time you verify that this word is only one character different from all the words behind it, you can build this ing dictionary and search for it in map every time.
What should we do? Another seemingly inconspicuous condition is that all words have the same length! Fortunately, there are a total of 26 English letters, and the search speed in set and map is very fast, and the word length is also the same, so we will try to change one character each time, check whether the change is required? If not, check that the dictionary is not in the dictionary and has not been accessed and added to the next layer. After trying this wave, restore the changed location, so that there is only one difference at a time. A little violent, but it works.
Ac code:
class Solution {public: int ladderLength(string start, string end, unordered_set
&dict) { if(start == end) return 2; if(dict.size()<=0) return 0; queue
que; set
visited; int res = 2, len = start.length(); que.push(start); que.push(""); bool flag = false; string tps(start); char tp; while(!que.empty()){ tps = que.front(); que.pop(); if(tps == ""){ if(que.empty()){ return 0; }else{ res++; que.push(""); continue; } } for(int i=0;i