1
+ #include " header.h"
2
+ #include < array>
3
+ #include < bits/c++config.h>
4
+ #include < cstddef>
5
+ #include < cstring>
6
+ #include < iostream>
7
+ #include < vector>
8
+
9
+
10
+ #define LEN 5001
11
+ class Solution {
12
+ public:
13
+ vector<vector<string>> findLadders (string beginWord, string endWord, vector<string>& wordList) {
14
+ const size_t &n = wordList.size ();
15
+ bool *end = new bool [n]();
16
+ bool *visited = new bool [n]();
17
+ bool begin;
18
+ bool hasEnd = false ;
19
+ queue<pair<int , vector<int >>> q;
20
+ for (size_t i=0 ; i<wordList.size (); i++) {
21
+ if (transfer (beginWord, wordList[i])) begin = true ;
22
+ else begin=false ;
23
+ if (transfer (endWord, wordList[i])) end[i] = true ;
24
+ if (endWord == wordList[i]) hasEnd = true ;
25
+ if (begin) {
26
+ vector<int > r = {(int )i};
27
+ q.emplace (i,r);
28
+ // visited[i] = true;
29
+ }
30
+ }
31
+ if (!hasEnd) return {};
32
+ if (transfer (beginWord, endWord)) {
33
+ vector<vector<string>> ret;
34
+ ret.push_back ({beginWord, endWord});
35
+ return ret;
36
+ }
37
+ static int map[LEN][LEN];
38
+ for (size_t i=0 ; i<n; i++)
39
+ map[i][0 ] = 0 ;
40
+ for (size_t i=0 ; i<n; i++) {
41
+ for (size_t j=i+1 ; j<n; j++) {
42
+ if (transfer (wordList[i], wordList[j])) {
43
+ map[i][++map[i][0 ]] = j;
44
+ map[j][++map[j][0 ]] = i;
45
+ }
46
+ }
47
+ }
48
+ bool found = false ;
49
+ int minStep = 100 ;
50
+
51
+ vector<vector<string>> ret;
52
+
53
+ while (!q.empty ()) {
54
+ int _last = q.front ().first ;
55
+ vector<int > _step = q.front ().second ;
56
+ visited[_last] = true ;
57
+ if (end[_last]&& _step.size ()<=minStep) {
58
+ minStep = _step.size ();
59
+ found = true ;
60
+ vector<string> a;
61
+ a.push_back (beginWord);
62
+ for (const auto &i:_step)
63
+ a.push_back (wordList[i]);
64
+ a.push_back (endWord);
65
+ ret.push_back (a);
66
+ }
67
+ else if (!found || _step.size ()<=minStep)
68
+ for (int i=1 ; i<=map[_last][0 ]; i++) {
69
+ int j = map[_last][i];
70
+ if (!visited[j]) {
71
+ _step.push_back (j);
72
+ q.emplace (j, _step);
73
+ _step.pop_back ();
74
+ }
75
+ }
76
+ q.pop ();
77
+ }
78
+ return ret;
79
+ }
80
+ private:
81
+ bool transfer (const string &a,const string &b) {
82
+ int differ = 0 ;
83
+ if (a.size ()!=b.size ()) return false ;
84
+ for (size_t i=0 ; i<a.size (); i++)
85
+ if (a[i]!=b[i]) {
86
+ differ++;
87
+ if (differ>1 ) return false ;
88
+ }
89
+ if (differ==1 )
90
+ return true ;
91
+ else
92
+ return false ;
93
+ }
94
+ };
95
+
96
+ int main () {
97
+ string beginWord = " red" ;
98
+ string endWord = " tax" ;
99
+ vector<string> wordList = {" ted" ," tex" ," red" ," tax" ," tad" ," den" ," rex" ," pee" };
100
+ auto s = Solution ().findLadders (beginWord, endWord, wordList);
101
+ for (auto v1:s) {
102
+ for (auto v2:v1) {
103
+ cout << v2 << " " ;
104
+ }
105
+ cout << endl;
106
+ }
107
+
108
+ return 0 ;
109
+ }
0 commit comments