Skip to content

Commit 14b8f65

Browse files
Update Word_Ladder_II.cpp
1 parent 24c99f0 commit 14b8f65

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

Word Ladder II/Word_Ladder_II.cpp

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,67 @@ class Solution
100100
res.push_back(tempRes);
101101
}
102102
}
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

Comments
 (0)