1
+ #include " header.h"
2
+ #include < array>
3
+ #include < bits/c++config.h>
4
+ #include < cstddef>
5
+ #include < cstring>
6
+ #include < vector>
7
+
8
+
9
+ #define LEN 5001
10
+ class Solution {
11
+ public:
12
+ int ladderLength (string beginWord, string endWord, vector<string>& wordList) {
13
+ array<bool , LEN> end;
14
+ array<bool , LEN> visited;
15
+ visited.fill (false );
16
+ bool begin;
17
+ bool hasEnd = false ;
18
+ end.fill (false );
19
+ queue<pair<int , 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
+ q.emplace (i,2 );
27
+ visited[i] = true ;
28
+ }
29
+ }
30
+ if (!hasEnd) return 0 ;
31
+ if (transfer (beginWord, endWord)) return 2 ;
32
+ const size_t &n = wordList.size ();
33
+ static int map[LEN][LEN];
34
+ for (size_t i=0 ; i<n; i++)
35
+ map[i][0 ] = 0 ;
36
+ for (size_t i=0 ; i<n; i++) {
37
+ for (size_t j=i+1 ; j<n; j++) {
38
+ if (transfer (wordList[i], wordList[j])) {
39
+ map[i][++map[i][0 ]] = j;
40
+ map[j][++map[j][0 ]] = i;
41
+ }
42
+ }
43
+ }
44
+
45
+ while (!q.empty ()) {
46
+ int _last = q.front ().first ;
47
+ int _step = q.front ().second ;
48
+ if (end[_last]) {
49
+ return _step+1 ;
50
+ }
51
+
52
+ for (int i=1 ; i<=map[_last][0 ]; i++) {
53
+ int j = map[_last][i];
54
+ if (!visited[j]) {
55
+ q.emplace (j, _step+1 );
56
+ visited[j] = true ;
57
+ }
58
+ }
59
+ q.pop ();
60
+ }
61
+ return 0 ;
62
+ }
63
+ private:
64
+ bool transfer (const string &a,const string &b) {
65
+ int differ = 0 ;
66
+ if (a.size ()!=b.size ()) return false ;
67
+ for (size_t i=0 ; i<a.size (); i++)
68
+ if (a[i]!=b[i]) {
69
+ differ++;
70
+ if (differ>1 ) return false ;
71
+ }
72
+ if (differ==1 )
73
+ return true ;
74
+ else
75
+ return false ;
76
+ }
77
+ };
78
+
79
+ int main () {
80
+ string beginWord = " a" ;
81
+ string endWord = " c" ;
82
+ vector<string> wordList = {" a" , " b" , " c" };
83
+ cout << Solution ().ladderLength (beginWord, endWord, wordList) << endl;
84
+
85
+ return 0 ;
86
+ }
0 commit comments