forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAC_two_end_BFS_n.cpp
75 lines (65 loc) · 1.98 KB
/
AC_two_end_BFS_n.cpp
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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_two_end_BFS_n.cpp
* Create Date: 2015-03-29 14:11:47
* Descripton:
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class Solution {
// it cost a lot of time
// private:
// bool checkChar(string &str1, string &str2) {
// int diff = 0;
// for (int i = 0; i < str1.length(); ++i) {
// if (str1[i] != str2[i])
// ++diff;
// if (diff > 1)
// return false;
// }
// return diff == 1;
// }
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
// use unordered_set as queue
unordered_set<string> startSet, endSet, *set1, *set2;
startSet.insert(start);
endSet.insert(end);
int dis = 1, len = start.length();
while (!startSet.empty() && !endSet.empty()) {
if (startSet.size() > endSet.size()) {
set1 = &startSet;
set2 = &endSet;
} else {
set1 = &endSet;
set2 = &startSet;
}
++dis;
unordered_set<string> newset1;
for (auto itr = set1->begin(); itr != set1->end(); itr++) {
string old = *itr;
for (int i = 0; i < len; ++i) {
char tmp = old[i];
for (int j = 0; j < 26; ++j) {
old[i] = 'a' + j;
auto f = set2->find(old);
if (f != set2->end())
return dis;
f = dict.find(old);
if (f != dict.end()) {
newset1.insert(old);
dict.erase(f);
}
}
old[i] = tmp;
}
}
swap(newset1, *set1);
}
return 0;
}
};
int main() {
return 0;
}