-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127-Word-Ladder.cpp
More file actions
37 lines (33 loc) · 998 Bytes
/
Copy path127-Word-Ladder.cpp
File metadata and controls
37 lines (33 loc) · 998 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
29
30
31
32
33
34
35
36
37
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string>st;
for(auto&it:wordList){
st.insert(it);
}
if(!st.count(endWord))return 0;
queue<string>q;
q.push(beginWord);
int ladder=1;
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;i++){
string word=q.front();
q.pop();
for(int j=0;j<word.size();j++){
string nextWord=word;
for(char k='a';k<='z';k++){
nextWord[j]=k;
if(nextWord==endWord)return ladder+1;
if(st.count(nextWord)){
q.push(nextWord);
st.erase(nextWord);
}
}
}
}
ladder++;
}
return 0;
}
};