File tree Expand file tree Collapse file tree 1 file changed +26
-15
lines changed Expand file tree Collapse file tree 1 file changed +26
-15
lines changed Original file line number Diff line number Diff line change 1+
2+
13class Solution {
24public:
35 int ladderLength (string beginWord, string endWord, vector<string>& wordList) {
46 unordered_set<string> dict (begin (wordList), end (wordList));
5- unordered_map<string, int > dis; // store the distance from start to the current word
6- queue<string> q; // FIFO for bfs purpose
7- dis[beginWord] = 1 ;
7+ queue<string> q;
88 q.push (beginWord);
9+ unordered_set<string> visited;
10+ visited.insert (beginWord);
11+ int step = 1 ;
912 while (!q.empty ()) {
10- string word = q.front ();
11- q.pop ();
12- if (word == endWord) break ;
13- for (int i = 0 ; i < word.size (); i++) {
14- for (int j = 0 ; j < 26 ; j++) {
15- string newWord = word;
16- newWord[i] = ' a' + j;
17- if (dict.count (newWord) > 0 && dis.count (newWord) == 0 ) {
18- dis[newWord] = dis[word] + 1 ;
19- q.push (newWord);
13+ int k = q.size ();
14+ for (int i = 0 ; i < k; i++) {
15+ string word = q.front ();
16+ q.pop ();
17+ if (word == endWord) {
18+ return step;
19+ }
20+ for (int i = 0 ; i < word.size (); i++) {
21+ char ch = word[i];
22+ for (int j = 0 ; j < 26 ; j++) {
23+ word[i] = ' a' + j;
24+ if (visited.count (word) == 0 && dict.count (word) > 0 ) {
25+ visited.insert (word);
26+ q.push (word);
27+ }
2028 }
29+ word[i] = ch;
2130 }
2231 }
32+
33+ step++;
2334 }
24- if (dis. count (endWord) == 0 ) return 0 ;
25- return dis[endWord] ;
35+
36+ return 0 ;
2637 }
2738};
You can’t perform that action at this time.
0 commit comments