-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP126.cpp
109 lines (103 loc) · 3.19 KB
/
P126.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
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
106
107
108
109
#include "header.h"
#include <array>
#include <bits/c++config.h>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <vector>
#define LEN 5001
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
const size_t &n = wordList.size();
bool *end = new bool[n]();
bool *visited = new bool[n]();
bool begin;
bool hasEnd = false;
queue<pair<int, vector<int>>> q;
for (size_t i=0; i<wordList.size(); i++) {
if (transfer(beginWord, wordList[i])) begin = true;
else begin=false;
if (transfer(endWord, wordList[i])) end[i] = true;
if (endWord == wordList[i]) hasEnd = true;
if (begin) {
vector<int> r = {(int)i};
q.emplace(i,r);
// visited[i] = true;
}
}
if (!hasEnd) return {};
if (transfer(beginWord, endWord)) {
vector<vector<string>> ret;
ret.push_back({beginWord, endWord});
return ret;
}
static int map[LEN][LEN];
for (size_t i=0; i<n; i++)
map[i][0] = 0;
for (size_t i=0; i<n; i++) {
for (size_t j=i+1; j<n; j++) {
if (transfer(wordList[i], wordList[j])) {
map[i][++map[i][0]] = j;
map[j][++map[j][0]] = i;
}
}
}
bool found = false;
int minStep = 100;
vector<vector<string>> ret;
while (!q.empty()) {
int _last = q.front().first;
vector<int> _step = q.front().second;
visited[_last] = true;
if (end[_last]&& _step.size()<=minStep) {
minStep = _step.size();
found = true;
vector<string> a;
a.push_back(beginWord);
for (const auto &i:_step)
a.push_back(wordList[i]);
a.push_back(endWord);
ret.push_back(a);
}
else if (!found || _step.size()<=minStep)
for (int i=1; i<=map[_last][0]; i++) {
int j = map[_last][i];
if (!visited[j]) {
_step.push_back(j);
q.emplace(j, _step);
_step.pop_back();
}
}
q.pop();
}
return ret;
}
private:
bool transfer(const string &a,const string &b) {
int differ = 0;
if (a.size()!=b.size()) return false;
for (size_t i=0; i<a.size(); i++)
if (a[i]!=b[i]) {
differ++;
if (differ>1) return false;
}
if (differ==1)
return true;
else
return false;
}
};
int main() {
string beginWord = "red";
string endWord = "tax";
vector<string> wordList = {"ted","tex","red","tax","tad","den","rex","pee"};
auto s = Solution().findLadders(beginWord, endWord, wordList);
for (auto v1:s) {
for (auto v2:v1) {
cout << v2 << " ";
}
cout << endl;
}
return 0;
}