@@ -100,4 +100,67 @@ class Solution
100
100
res.push_back (tempRes);
101
101
}
102
102
}
103
- };
103
+ };
104
+
105
+ // 第二种思路,单独使用BFS
106
+ // 存储的不再是string,而是由string组成的路径,附参考链接
107
+ // https://leetcode.com/problems/word-ladder-ii/discuss/40434/C%2B%2B-solution-using-standard-BFS-method-no-DFS-or-backtracking
108
+
109
+ // 做题过程中发现一个最大的不同就是每一层是可以使用同样的单词的
110
+
111
+ // Runtime: 468 ms, faster than 39.17% of C++ online submissions for Word Ladder II.
112
+ // Memory Usage: 184.2 MB, less than 5.31% of C++ online submissions for Word Ladder II.
113
+
114
+ class Solution
115
+ {
116
+ public:
117
+ vector<vector<string>> findLadders (string beginWord, string endWord, vector<string>& wordList)
118
+ {
119
+ vector<vector<string>> res;
120
+ queue<vector<string>> paths;
121
+ unordered_set<string> hashset (wordList.begin (), wordList.end ());
122
+
123
+ paths.push (vector<string>(1 , beginWord));
124
+
125
+ bool found = false ;
126
+ while (!paths.empty () && !found)
127
+ {
128
+ vector<string> visited;
129
+ for (int i = paths.size (); i > 0 ; --i)
130
+ {
131
+ vector<string> path = paths.front ();
132
+ paths.pop ();
133
+
134
+ string word = path.back ();
135
+ for (int j = 0 ; j < word.size (); ++j)
136
+ {
137
+ char chr = word[j];
138
+ for (int k = 0 ; k < 26 ; ++k)
139
+ {
140
+ word[j] = k + ' a' ;
141
+ if (hashset.find (word) != hashset.end ())
142
+ {
143
+ vector<string> newPath = path;
144
+ newPath.push_back (word);
145
+
146
+ if (word == endWord)
147
+ {
148
+ res.push_back (newPath);
149
+ found = true ;
150
+ }
151
+ else
152
+ {
153
+ visited.push_back (word);
154
+ paths.push (newPath);
155
+ }
156
+ }
157
+ }
158
+ word[j] = chr;
159
+ }
160
+ }
161
+ for (auto item : visited)
162
+ hashset.erase (item);
163
+ }
164
+ return res;
165
+ }
166
+ };
0 commit comments