-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWord Ladder.cpp
More file actions
28 lines (28 loc) · 924 Bytes
/
Copy pathWord Ladder.cpp
File metadata and controls
28 lines (28 loc) · 924 Bytes
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
class Solution {
public:
int ladderLength(string startWord, string targetWord, vector<string>& wordList) {
queue<pair<string, int>> q;
q.push({startWord, 1});
set<string> st(wordList.begin(), wordList.end());
st.erase(startWord);
while (!q.empty()){
string word = q.front().first;
int steps = q.front().second;
q.pop();
if (word == targetWord) return steps;
for (int i = 0; i < word.size(); i++){
char original = word[i];
for (char ch = 'a'; ch <= 'z'; ch++){
word[i] = ch;
if (st.find(word) != st.end())
{
st.erase(word);
q.push({word, steps + 1});
}
}
word[i] = original;
}
}
return 0;
}
};