1
1
package Problem0126
2
2
3
3
func findLadders (beginWord string , endWord string , words []string ) [][]string {
4
- res := [][]string {}
5
- // 因为 beginWord 不能做 transformed word
6
- // 很碍事,就先删掉,好让后面的逻辑简明一些
4
+ // 因为 beginWord 不能做 transformed word 很碍事,就先删掉,好让后面的逻辑简明一些
7
5
words = deleteBeginWord (words , beginWord )
8
6
7
+ // trans 用来记录 k -> v[i] 的转换关系。
9
8
trans := map [string ][]string {}
9
+ // isMatchedEndWord 用于在生成 trans 的过程中,存在 -> endWord 的转换关系
10
+ // 用于提前结束
10
11
isMatchedEndWord := false
12
+ // cnt 用于记录生成trans的迭代次数
13
+ // 其实也是最短路径的长度
11
14
cnt := 1
12
15
var bfs func ([]string , []string )
13
-
16
+ // 使用 bfs 方法,递归地生成 trans
14
17
bfs = func (words , nodes []string ) {
15
18
cnt ++
19
+ // words 中的 w
20
+ // 与 nodes 中的 n -> w,在 w 会被放入 newNodes
21
+ // 否则,w 会被放入 newWords
16
22
newWords := make ([]string , 0 , len (words ))
17
23
newNodes := make ([]string , 0 , len (words ))
18
24
for _ , w := range words {
@@ -33,17 +39,22 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
33
39
}
34
40
}
35
41
36
- if isMatchedEndWord || len (newWords ) == 0 || len (newNodes ) == 0 {
42
+ if isMatchedEndWord || // 匹配到 endWord 说明已经找到了所有的最短路径
43
+ len (newWords ) == 0 || // 全部匹配完成
44
+ len (newNodes ) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
37
45
return
38
46
}
39
47
48
+ // 继续完善 trans
40
49
bfs (newWords , newNodes )
41
50
}
42
51
43
52
nodes := []string {beginWord }
44
53
bfs (words , nodes )
45
54
55
+ res := [][]string {}
46
56
if ! isMatchedEndWord {
57
+ // beginWord 无法 trans 到 endWord
47
58
return res
48
59
}
49
60
0 commit comments