Skip to content

Commit 07ff704

Browse files
committed
bfs
1 parent da9c853 commit 07ff704

File tree

2 files changed

+215
-42
lines changed

2 files changed

+215
-42
lines changed

Diff for: leetcode/126.word_ladder_ii/126.WordLadderII_henrytine.cpp

+112-42
Original file line numberDiff line numberDiff line change
@@ -2,117 +2,187 @@
22
// Author : henrytine
33
// Date : 2020-08-11
44

5-
/*****************************************************************************************************
5+
/*****************************************************************************************************
66
*
7-
* Given two words (beginWord and endWord), and a dictionary's word list, find all shortest
7+
* Given two words (beginWord and endWord), and a dictionary's word list, find all shortest
88
* transformation sequence(s) from beginWord to endWord, such that:
9-
*
9+
*
1010
* Only one letter can be changed at a time
11-
* Each transformed word must exist in the word list. Note that beginWord is not a transformed
11+
* Each transformed word must exist in the word list. Note that beginWord is not a transformed
1212
* word.
13-
*
13+
*
1414
* Note:
15-
*
15+
*
1616
* Return an empty list if there is no such transformation sequence.
1717
* All words have the same length.
1818
* All words contain only lowercase alphabetic characters.
1919
* You may assume no duplicates in the word list.
2020
* You may assume beginWord and endWord are non-empty and are not the same.
21-
*
21+
*
2222
* Example 1:
23-
*
23+
*
2424
* Input:
2525
* beginWord = "hit",
2626
* endWord = "cog",
2727
* wordList = ["hot","dot","dog","lot","log","cog"]
28-
*
28+
*
2929
* Output:
3030
* [
3131
* ["hit","hot","dot","dog","cog"],
3232
* ["hit","hot","lot","log","cog"]
3333
* ]
34-
*
34+
*
3535
* Example 2:
36-
*
36+
*
3737
* Input:
3838
* beginWord = "hit"
3939
* endWord = "cog"
4040
* wordList = ["hot","dot","dog","lot","log"]
41-
*
41+
*
4242
* Output: []
43-
*
43+
*
4444
* Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
45-
*
45+
*
4646
******************************************************************************************************/
4747

48-
#include <vector>
49-
#include <string>
50-
#include <unordered_set>
51-
#include <unordered_map>
52-
#include <queue>
53-
54-
using namespace std;
48+
#include "../inc/ac.h"
5549

56-
class Solution {
50+
class Solution1
51+
{
5752
public:
58-
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
53+
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
54+
{
5955
vector<vector<string>> res;
60-
unordered_set<string> visit; //notice we need to clear visited word in list after finish this level of BFS
56+
unordered_set<string> visit; // notice we need to clear visited word in list after finish this level of BFS
6157
queue<vector<string>> q;
6258
unordered_set<string> wordlist(wordList.begin(), wordList.end());
63-
q.push({ beginWord });
64-
bool flag = false; //to see if we find shortest path
65-
while (!q.empty()) {
59+
q.push({beginWord});
60+
bool flag = false; // to see if we find shortest path
61+
while (!q.empty())
62+
{
6663
int size = q.size();
67-
for (int i = 0; i<size; i++) { //for this level
64+
for (int i = 0; i < size; i++)
65+
{ // for this level
6866
vector<string> cur = q.front();
6967
q.pop();
7068
vector<string> newadd = addWord(cur.back(), wordlist);
71-
for (int j = 0; j<newadd.size(); j++) { //add a word into path
69+
for (int j = 0; j < newadd.size(); j++)
70+
{ // add a word into path
7271
vector<string> newline(cur.begin(), cur.end());
7372
newline.push_back(newadd[j]);
74-
if (newadd[j] == endWord) {
73+
if (newadd[j] == endWord)
74+
{
7575
flag = true;
7676
res.push_back(newline);
7777
}
7878
visit.insert(newadd[j]);
7979
q.push(newline);
8080
}
8181
}
82-
if (flag) break; //do not BFS further
83-
for (auto it = visit.begin(); it != visit.end(); it++) wordlist.erase(*it); //erase visited one
82+
if (flag)
83+
break; // do not BFS further
84+
for (auto it = visit.begin(); it != visit.end(); it++)
85+
wordlist.erase(*it); // erase visited one
8486
visit.clear();
8587
}
8688
return res;
8789
}
8890

8991
// find words with one char different in dict
9092
// hot->[dot,lot]
91-
vector<string> addWord(string word, unordered_set<string>& wordlist) {
93+
vector<string> addWord(string word, unordered_set<string> &wordlist)
94+
{
9295
vector<string> res;
93-
for (int i = 0; i<word.size(); i++) {
96+
for (int i = 0; i < word.size(); i++)
97+
{
9498
char s = word[i];
95-
for (char c = 'a'; c <= 'z'; c++) {
99+
for (char c = 'a'; c <= 'z'; c++)
100+
{
96101
word[i] = c;
97-
if (wordlist.count(word)) res.push_back(word);
102+
if (wordlist.count(word))
103+
res.push_back(word);
98104
}
99105
word[i] = s;
100106
}
101107
return res;
102108
}
103109
};
104110

111+
class Solution
112+
{
113+
public:
114+
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
115+
{
116+
set<string> dict(wordList.begin(), wordList.end());
105117

118+
queue<vector<string>> que;
119+
que.push({beginWord});
120+
vector<vector<string>> ans;
106121

107-
//#if DEBUG
108-
int main(int argc, char** argv) {
122+
while (!que.empty())
123+
{
124+
int len = que.size();
125+
for (int j = 0; j < len; j++)
126+
{
127+
vector<string> seq = que.front();
128+
que.pop();
129+
130+
// Insert a path solution.
131+
if (seq.back() == endWord)
132+
{
133+
ans.push_back(seq);
134+
continue;
135+
}
109136

110-
Solution a;
137+
// Find neighbors.
138+
string word = seq.back();
139+
for (int i = 0; i < word.size(); i++)
140+
{
141+
string newWord = seq.back();
142+
for (char ch = 'a'; ch <= 'z'; ch++)
143+
{
144+
newWord[i] = ch;
145+
146+
if (!dict.count(newWord))
147+
{
148+
continue;
149+
}
150+
151+
dict.erase(word);
152+
que.push(seq);
153+
que.back().push_back(newWord);
154+
}
155+
}
156+
}
157+
158+
if (not ans.empty())
159+
{
160+
break;
161+
}
162+
}
163+
164+
return ans;
165+
}
166+
};
167+
168+
//#if DEBUG
169+
int main(int argc, char **argv)
170+
{
111171

112172
string beginWord = "hit", endWord = "cog";
113-
vector<string> wordList = { "hot", "dot", "dog", "lot", "log", "cog" };
114-
115-
a.findLadders(beginWord, endWord, wordList);
173+
vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"};
174+
175+
auto ans = Solution().findLadders(beginWord, endWord, wordList);
176+
for (auto &&iter : ans)
177+
{
178+
for (auto &&subiter : iter)
179+
{
180+
cout << subiter << " ";
181+
}
182+
cout << "\n";
183+
}
184+
cout << "\n";
185+
116186
return 0;
117187
}
118188
//#endif

Diff for: leetcode/127.word_ladder/127.wordLadder_eveshen.java

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Source : https://leetcode.com/problems/word-ladder/
2+
// Author: Eve
3+
// Date: 2020-07-31
4+
5+
/*****************************************************************************************************
6+
*
7+
* Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest
8+
* transformation sequence from beginWord to endWord, such that:
9+
*
10+
* Only one letter can be changed at a time.
11+
* Each transformed word must exist in the word list.
12+
*
13+
* Note:
14+
*
15+
* Return 0 if there is no such transformation sequence.
16+
* All words have the same length.
17+
* All words contain only lowercase alphabetic characters.
18+
* You may assume no duplicates in the word list.
19+
* You may assume beginWord and endWord are non-empty and are not the same.
20+
*
21+
* Example 1:
22+
*
23+
* Input:
24+
* beginWord = "hit",
25+
* endWord = "cog",
26+
* wordList = ["hot","dot","dog","lot","log","cog"]
27+
*
28+
* Output: 5
29+
*
30+
* Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
31+
* return its length 5.
32+
*
33+
* Example 2:
34+
*
35+
* Input:
36+
* beginWord = "hit"
37+
* endWord = "cog"
38+
* wordList = ["hot","dot","dog","lot","log"]
39+
*
40+
* Output: 0
41+
*
42+
* Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
43+
******************************************************************************************************/
44+
45+
// BFS
46+
class Solution {
47+
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
48+
if (!wordList.contains(endWord)) {
49+
return 0;
50+
}
51+
// Delete the duplicates.
52+
Set<String> set = new HashSet<>(wordList);
53+
// Add the potentil words.
54+
Queue<String> queue = new LinkedList<>();
55+
queue.add(beginWord);
56+
// Count the steps.
57+
int count = 1;
58+
while (!queue.isEmpty()) {
59+
int size = queue.size();
60+
// Traverse every word in the same level.
61+
for (int i = 0; i < size; i++) {
62+
String word = queue.poll();
63+
// Terminate.
64+
if (word.equals(endWord)) {
65+
return count;
66+
}
67+
// Check the validation.
68+
isValid(word, set, queue);
69+
}
70+
// Begin another round.
71+
count++;
72+
}
73+
return 0;
74+
}
75+
76+
private void isValid(String word, Set<String> set, Queue<String> queue) {
77+
// Loop over the word and check all the characters.
78+
for (int i = 0; i < word.length(); i++) {
79+
// Change the string to list of characters.
80+
char[] chr = word.toCharArray();
81+
// Try all the possibilities.
82+
for (char j = 'a'; j <= 'z'; j++) {
83+
if (chr[i] == j) {
84+
continue;
85+
}
86+
chr[i] = j;
87+
// Transform characters to string.
88+
String newWord = String.valueOf(chr);
89+
// If the word is in the word list, we can use it.
90+
// Delete it from the set to avoid repeated calculation.
91+
if (set.contains(newWord)) {
92+
set.remove(newWord);
93+
queue.offer(newWord);
94+
}
95+
}
96+
}
97+
98+
}
99+
}
100+
// Time Complexity: O(m * 26 * n), m is the length of words, n is the number of words.
101+
// Space Complexity: O(m * 26 * n)
102+
103+

0 commit comments

Comments
 (0)