-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127_ladder_length.cc
75 lines (71 loc) · 1.9 KB
/
127_ladder_length.cc
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
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
using namespace::std;
class Solution {
public:
int diffcnt(string& s1, string &s2) {
int cnt = 0;
for (int i = 0; i < (int)s1.size(); ++i) {
if (s1[i] != s2[i])
++cnt;
if (cnt > 1)
break;
}
return cnt;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
wordList.push_back(beginWord);
int n = wordList.size();
vector<vector<int>> graph(n);
vector<int> visited(n, 0);
vector<int> que(1, n - 1), next_que;
visited[n - 1] = 1;
int deep = 1;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (diffcnt(wordList[i], wordList[j]) < 2) {
graph[i].push_back(j);
graph[j].push_back(i);
}
}
}
int target = -1;
for (int i = 0; i < n; ++i) {
if (diffcnt(wordList[i], endWord) == 0) {
target = i;
break;
}
}
if (target == -1)
return 0;
while (!que.empty()) {
++deep;
for (int i = 0; i < que.size(); ++i) {
int src = que[i];
for (int j = 0; j < graph[src].size(); ++j) {
int next = graph[src][j];
if (next == target)
return deep;
if (!visited[next]) {
visited[next] = 1;
next_que.push_back(next);
}
}
}
swap(que, next_que);
next_que.clear();
}
return 0;
}
};
int main()
{
return 0;
}