-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathWordLadder.cpp
More file actions
92 lines (80 loc) · 2.51 KB
/
Copy pathWordLadder.cpp
File metadata and controls
92 lines (80 loc) · 2.51 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <set>
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
set<string> s;
for(string str: wordList) {
s.insert(str);
}
s.insert(beginWord);
map<string, vector<string>> map;
buildGraph(map, s);
set<string> visited;
queue<string> q;
q.push(beginWord);
int level = 0;
while(!q.empty()) {
int size = q.size();
while(size-- > 0) {
string head = q.front();
q.pop();
if(head == endWord) {
return level+1;
}
if(visited.find(head) != visited.end()) {
continue;
}
for(string connection: map[head]) {
if(!visited.count(connection)) {
q.push(connection);
}
}
visited.insert(head);
}
level++;
}
if(visited.count(endWord)) {
return level;
} else {
return 0;
}
}
void buildGraph(map<string, vector<string>> map, set<string> wordSet) {
for(string el: wordSet) {
for(string innerEl: wordSet) {
if(el == innerEl) {
continue;
} else {
if(stringsDifferByOne(el, innerEl)) {
// el to innerEl
vector<string> connections = map[el];
connections.push_back(innerEl);
map[el] = connections;
// innerEl to El
vector<string> connectionsForIEl = map[innerEl];
connectionsForIEl.push_back(el);
map[innerEl] = connectionsForIEl;
}
}
}
}
}
bool stringsDifferByOne(string a, string b) {
if(a.size() != b.size()) {
return false;
} else {
bool foundOneDifference = false;
for(int i=0; i<a.size(); i++) {
char aChar = a[i];
char bChar = b[i];
if(aChar != bChar) {
if(foundOneDifference) {
return false;
}
foundOneDifference = true;
}
}
}
return true;
}
};