forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0127-word-ladder.cpp
55 lines (44 loc) · 1.6 KB
/
0127-word-ladder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Given 2 words & a dictionary, return min # of words to transform b/w them
Ex. begin = "hit", end = "cog", dict = ["hot","dot","dog","lot","log","cog"] -> 5
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
BFS, change 1 letter at a time (neighbors), if in dict add to queue, else skip
Time: O(m^2 x n) -> m = length of each word, n = # of words in input word list
Space: O(m^2 x n)
*/
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> dict;
for (int i = 0; i < wordList.size(); i++) {
dict.insert(wordList[i]);
}
queue<string> q;
q.push(beginWord);
int result = 1;
while (!q.empty()) {
int count = q.size();
for (int i = 0; i < count; i++) {
string word = q.front();
q.pop();
if (word == endWord) {
return result;
}
dict.erase(word);
for (int j = 0; j < word.size(); j++) {
char c = word[j];
for (int k = 0; k < 26; k++) {
word[j] = k + 'a';
if (dict.find(word) != dict.end()) {
q.push(word);
dict.erase(word);
}
word[j] = c;
}
}
}
result++;
}
return 0;
}
};