11package Problem0126
22
33func findLadders (beginWord string , endWord string , words []string ) [][]string {
4- // 因为 beginWord 不能做 transformed word 很碍事,就先删掉,好让后面的逻辑简明一些
4+ // 因为 beginWord 不能做 transformed word
5+ // 先删掉 words 中的 beginWord,
6+ // 可以让后面的 trans 少很多的断头 path,会加快程序。
7+ // 也更符合题意
8+ // 删除下面这句,程序也能 accepted,但是会从 269ms 减慢到 319ms
59 words = deleteBeginWord (words , beginWord )
610
7- // trans 用来记录 k -> v[i] 的转换关系。
11+ // trans 用来查找 k->?
812 trans := map [string ][]string {}
9- // isMatchedEndWord 用于在生成 trans 的过程中 ,存在 -> endWord 的转换关系
13+ // isTransedEndWord 用于在生成 trans 的过程中标记 ,存在 ->endWord 的转换关系
1014 // 用于提前结束
11- isMatchedEndWord := false
15+ isTransedEndWord := false
1216 // cnt 用于记录生成trans的迭代次数
1317 // 其实也是最短路径的长度
1418 cnt := 1
@@ -17,43 +21,46 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
1721 bfs = func (words , nodes []string ) {
1822 cnt ++
1923 // words 中的 w
20- // 与 nodes 中的 n -> w,在 w 会被放入 newNodes
24+ // 与 nodes 中的 n ,可以实现 n->w 的转换,
25+ // 则,w 会被放入 newNodes
2126 // 否则,w 会被放入 newWords
2227 newWords := make ([]string , 0 , len (words ))
2328 newNodes := make ([]string , 0 , len (words ))
2429 for _ , w := range words {
25- isMatched := false
30+ isTransed := false
2631 for _ , n := range nodes {
27- if isTransable (w , n ) {
28- isMatched = true
32+ if isTransable (n , w ) {
2933 trans [n ] = append (trans [n ], w )
34+ isTransed = true
3035 }
3136 }
32- if isMatched {
37+
38+ if isTransed {
3339 newNodes = append (newNodes , w )
3440 if w == endWord {
35- isMatchedEndWord = true
41+ isTransedEndWord = true
3642 }
3743 } else {
3844 newWords = append (newWords , w )
3945 }
4046 }
4147
42- if isMatchedEndWord || // 匹配到 endWord 说明已经找到了所有的最短路径
43- len (newWords ) == 0 || // 全部匹配完成
48+ if isTransedEndWord || // 转换到了 endWord 说明已经找到了所有的最短路径
49+ len (newWords ) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
4450 len (newNodes ) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
4551 return
4652 }
4753
48- // 继续完善 trans
54+ // 上面没有 return,要继续完善 trans
4955 bfs (newWords , newNodes )
5056 }
5157
58+ // 第一代 nodes 含有且仅含有 beginWord
5259 nodes := []string {beginWord }
5360 bfs (words , nodes )
5461
5562 res := [][]string {}
56- if ! isMatchedEndWord {
63+ if ! isTransedEndWord {
5764 // beginWord 无法 trans 到 endWord
5865 return res
5966 }
@@ -75,7 +82,7 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
7582
7683 prev := path [idx - 1 ]
7784 for _ , w := range trans [prev ] {
78- // 利用 prev -> w 填充 path[idx]
85+ // 利用 prev-> w 填充 path[idx]
7986 path [idx ] = w
8087 dfs (idx + 1 )
8188 }
@@ -92,6 +99,8 @@ func deepCopy(src []string) []string {
9299 return temp
93100}
94101
102+ // 题目中说了,words 中没有重复的单词,
103+ // 所以,beginWord 最多出现一次
95104func deleteBeginWord (words []string , beginWord string ) []string {
96105 i := 0
97106 for ; i < len (words ); i ++ {
0 commit comments