-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127.cpp
More file actions
42 lines (35 loc) · 992 Bytes
/
127.cpp
File metadata and controls
42 lines (35 loc) · 992 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
38
39
40
41
42
// Word ladder
// HARD
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> st;
for (const string& s : wordList) {
st.insert(s);
}
queue<pair<string, int>> q;
q.push({beginWord, 1});
st.insert(beginWord);
while (!q.empty()) {
auto [word, pos] = q.front();
q.pop();
st.erase(word);
if (word == endWord) {
return pos;
}
for (int i = 0; i < word.length(); i ++) {
string temp = word;
temp[i] = 'a';
for (int j = 0; j < 26; j ++) {
if (st.count(temp) && temp != word) {
q.push({temp, pos + 1});
}
temp[i] ++;
}
}
}
return 0;
}
};