Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 90fcde6

Browse files
aQuaaQua
aQua
authored and
aQua
committed
126 注释了程序的上半部分
1 parent 2cab3ac commit 90fcde6

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

Algorithms/0126.word-ladder-ii/word-ladder-ii.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
11
package Problem0126
22

33
func findLadders(beginWord string, endWord string, words []string) [][]string {
4-
res := [][]string{}
5-
// 因为 beginWord 不能做 transformed word
6-
// 很碍事,就先删掉,好让后面的逻辑简明一些
4+
// 因为 beginWord 不能做 transformed word 很碍事,就先删掉,好让后面的逻辑简明一些
75
words = deleteBeginWord(words, beginWord)
86

7+
// trans 用来记录 k -> v[i] 的转换关系。
98
trans := map[string][]string{}
9+
// isMatchedEndWord 用于在生成 trans 的过程中,存在 -> endWord 的转换关系
10+
// 用于提前结束
1011
isMatchedEndWord := false
12+
// cnt 用于记录生成trans的迭代次数
13+
// 其实也是最短路径的长度
1114
cnt := 1
1215
var bfs func([]string, []string)
13-
16+
// 使用 bfs 方法,递归地生成 trans
1417
bfs = func(words, nodes []string) {
1518
cnt++
19+
// words 中的 w
20+
// 与 nodes 中的 n -> w,在 w 会被放入 newNodes
21+
// 否则,w 会被放入 newWords
1622
newWords := make([]string, 0, len(words))
1723
newNodes := make([]string, 0, len(words))
1824
for _, w := range words {
@@ -33,17 +39,22 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
3339
}
3440
}
3541

36-
if isMatchedEndWord || len(newWords) == 0 || len(newNodes) == 0 {
42+
if isMatchedEndWord || // 匹配到 endWord 说明已经找到了所有的最短路径
43+
len(newWords) == 0 || // 全部匹配完成
44+
len(newNodes) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
3745
return
3846
}
3947

48+
// 继续完善 trans
4049
bfs(newWords, newNodes)
4150
}
4251

4352
nodes := []string{beginWord}
4453
bfs(words, nodes)
4554

55+
res := [][]string{}
4656
if !isMatchedEndWord {
57+
// beginWord 无法 trans 到 endWord
4758
return res
4859
}
4960

0 commit comments

Comments
 (0)