@@ -13,12 +13,11 @@ func ladderLength(beginWord string, endWord string, words []string) int {
13
13
isTransedEndWord := false
14
14
// cnt 用于记录生成trans的迭代次数
15
15
// 其实也是最短路径的长度
16
- // TODO: 修改 cnt 为 res
17
- cnt := 1
16
+ res := 1
18
17
var bfs func ([]string , []string )
19
18
// 使用 bfs 方法,递归地生成 trans
20
19
bfs = func (words , nodes []string ) {
21
- cnt ++
20
+ res ++
22
21
// words 中的 w
23
22
// 与 nodes 中的 n ,可以实现 n->w 的转换,
24
23
// 则,w 会被放入 newNodes
@@ -36,6 +35,7 @@ func ladderLength(beginWord string, endWord string, words []string) int {
36
35
37
36
if isTransed {
38
37
if w == endWord {
38
+ isTransedEndWord = true
39
39
return
40
40
}
41
41
newNodes = append (newNodes , w )
@@ -62,30 +62,25 @@ func ladderLength(beginWord string, endWord string, words []string) int {
62
62
return 0
63
63
}
64
64
65
- return cnt
66
- }
67
-
68
- func deepCopy (src []string ) []string {
69
- temp := make ([]string , len (src ))
70
- copy (temp , src )
71
- return temp
65
+ return res
72
66
}
73
67
74
68
// 题目中说了,words 中没有重复的单词,
75
69
// 所以,beginWord 最多出现一次
76
70
func deleteBeginWord (words []string , beginWord string ) []string {
77
- i := 0
78
- for ; i < len ( words ) ; i ++ {
71
+ i , size := 0 , len ( words )
72
+ for ; i < size ; i ++ {
79
73
if words [i ] == beginWord {
80
74
break
81
75
}
82
76
}
83
77
84
- if i == len ( words ) {
78
+ if i == size {
85
79
return words
86
80
}
87
81
88
- return append (words [:i ], words [i + 1 :]... )
82
+ words [i ] = words [size - 1 ]
83
+ return words [:size - 1 ]
89
84
}
90
85
91
86
func isTransable (a , b string ) bool {
0 commit comments