1
1
package Problem0127
2
2
3
- func ladderLength (beginWord string , endWord string , wordList []string ) int {
3
+ func ladderLength (beginWord string , endWord string , words []string ) int {
4
4
// 因为 beginWord 不能做 transformed word
5
5
// 先删掉 words 中的 beginWord,
6
6
// 可以让后面的 trans 少很多的断头 path,会加快程序。
7
7
// 也更符合题意
8
8
// 删除下面这句,程序也能 accepted,但是会从 269ms 减慢到 319ms
9
9
words = deleteBeginWord (words , beginWord )
10
10
11
- // trans 用来查找 k->?
12
- trans := map [string ][]string {}
13
11
// isTransedEndWord 用于在生成 trans 的过程中标记,存在 ->endWord 的转换关系
14
12
// 用于提前结束
15
13
isTransedEndWord := false
16
14
// cnt 用于记录生成trans的迭代次数
17
15
// 其实也是最短路径的长度
16
+ // TODO: 修改 cnt 为 res
18
17
cnt := 1
19
18
var bfs func ([]string , []string )
20
19
// 使用 bfs 方法,递归地生成 trans
@@ -30,23 +29,22 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
30
29
isTransed := false
31
30
for _ , n := range nodes {
32
31
if isTransable (n , w ) {
33
- trans [n ] = append (trans [n ], w )
34
32
isTransed = true
33
+ break
35
34
}
36
35
}
37
36
38
37
if isTransed {
39
- newNodes = append (newNodes , w )
40
38
if w == endWord {
41
- isTransedEndWord = true
39
+ return
42
40
}
41
+ newNodes = append (newNodes , w )
43
42
} else {
44
43
newWords = append (newWords , w )
45
44
}
46
45
}
47
46
48
- if isTransedEndWord || // 转换到了 endWord 说明已经找到了所有的最短路径
49
- len (newWords ) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
47
+ if len (newWords ) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
50
48
len (newNodes ) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
51
49
return
52
50
}
@@ -59,38 +57,12 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
59
57
nodes := []string {beginWord }
60
58
bfs (words , nodes )
61
59
62
- res := [][]string {}
63
60
if ! isTransedEndWord {
64
61
// beginWord 无法 trans 到 endWord
65
- return res
62
+ return 0
66
63
}
67
64
68
- path := make ([]string , cnt )
69
- path [0 ] = beginWord
70
-
71
- var dfs func (int )
72
- // 使用 dfs 方法,生成最短路径
73
- dfs = func (idx int ) {
74
- if idx == cnt {
75
- // path 已经填充完毕
76
- if path [idx - 1 ] == endWord {
77
- // 最后一个单词是 endWord,说明这是一条最短路径
78
- res = append (res , deepCopy (path ))
79
- }
80
- return
81
- }
82
-
83
- prev := path [idx - 1 ]
84
- for _ , w := range trans [prev ] {
85
- // 利用 prev->w 填充 path[idx]
86
- path [idx ] = w
87
- dfs (idx + 1 )
88
- }
89
- }
90
-
91
- dfs (1 )
92
-
93
- return res
65
+ return cnt
94
66
}
95
67
96
68
func deepCopy (src []string ) []string {
0 commit comments