-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127.cpp
More file actions
105 lines (100 loc) · 3.08 KB
/
127.cpp
File metadata and controls
105 lines (100 loc) · 3.08 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
93
94
95
96
97
98
99
100
101
102
103
104
105
//
// 127.cpp
// LeetCode
//
// Created by 张佐玮 on 15/8/16.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Word Ladder
//
#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;
class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
queue<string> current;
current.push(beginWord);
wordDict.erase(beginWord);
wordDict.insert(endWord);
int step = 1;
while (!current.empty()) {
int currentLen = (int) current.size();
while (currentLen--) {
string word = current.front();
current.pop();
if (word == endWord) {
return step;
}
for (int i = 0; i < word.size(); i++) {
char temp = word[i];
for (char j = 'a'; j <= 'z'; j++) {
if (j == temp) {
continue;
}
word[i] = j;
if (wordDict.find(word) != wordDict.end()) {
wordDict.erase(word);
current.push(word);
}
}
word[i] = temp;
}
}
step++;
}
return 0;
}
int ladderLengthBidir(string beginWord, string endWord, unordered_set<string>& wordDict) {
if (beginWord == endWord) {
return 1;
}
unordered_set<string> begin, end, *head, *tail;
int step = 2;
begin.insert(beginWord);
end.insert(endWord);
while (!begin.empty() && !end.empty()) {
if (begin.size() <= end.size()) {
head = &begin;
tail = &end;
}
else {
head = &end;
tail = &begin;
}
unordered_set<string> temp;
for (string current: *head) {
for (int i = 0; i < current.size(); i++) {
char ch = current[i];
for (char j = 'a'; j <= 'z'; j++) {
if (j == ch) {
continue;
}
current[i] = j;
if (tail -> find(current) != tail -> end()) {
return step;
}
if (wordDict.find(current) != wordDict.end()) {
wordDict.erase(current);
temp.insert(current);
}
}
current[i] = ch;
}
}
step++;
*head = temp;
}
return 0;
}
};
class Test {
public:
void sample() {
string b("hit"), e("cog");
unordered_set<string> wordDict({"hot","dot","dog","lot","log"});
Solution solution;
cout << solution.ladderLengthBidir(b, e, wordDict) << endl;
}
};