-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127.cpp
More file actions
29 lines (27 loc) · 936 Bytes
/
127.cpp
File metadata and controls
29 lines (27 loc) · 936 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
class Solution {
public:
bool offByOne(string& s, string& t){
bool off = false;
for(int i = 0; i < s.length(); i++){
if(!off && s[i] != t[i]) off = true;
else if(off && s[i] != t[i]) return false;
}
return off;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) { //straightforward BFS
int n = wordList.size(); wordList.push_back(beginWord);
vector<int> visited(n+1);
queue<int> q; q.push(n);
while(!q.empty()){
int x = q.front(); q.pop();
for(int i = 0; i < wordList.size(); i++){
if(!visited[i] && offByOne(wordList[x], wordList[i])){
visited[i] = visited[x] + 1;
q.push(i);
if(wordList[i] == endWord) return visited[i]+1;
}
}
}
return 0;
}
};