11package Problem0127
22
3- func ladderLength (beginWord string , endWord string , wordList []string ) int {
3+ func ladderLength (beginWord string , endWord string , words []string ) int {
44 // 因为 beginWord 不能做 transformed word
55 // 先删掉 words 中的 beginWord,
66 // 可以让后面的 trans 少很多的断头 path,会加快程序。
77 // 也更符合题意
88 // 删除下面这句,程序也能 accepted,但是会从 269ms 减慢到 319ms
99 words = deleteBeginWord (words , beginWord )
1010
11- // trans 用来查找 k->?
12- trans := map [string ][]string {}
1311 // isTransedEndWord 用于在生成 trans 的过程中标记,存在 ->endWord 的转换关系
1412 // 用于提前结束
1513 isTransedEndWord := false
1614 // cnt 用于记录生成trans的迭代次数
1715 // 其实也是最短路径的长度
16+ // TODO: 修改 cnt 为 res
1817 cnt := 1
1918 var bfs func ([]string , []string )
2019 // 使用 bfs 方法,递归地生成 trans
@@ -30,23 +29,22 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
3029 isTransed := false
3130 for _ , n := range nodes {
3231 if isTransable (n , w ) {
33- trans [n ] = append (trans [n ], w )
3432 isTransed = true
33+ break
3534 }
3635 }
3736
3837 if isTransed {
39- newNodes = append (newNodes , w )
4038 if w == endWord {
41- isTransedEndWord = true
39+ return
4240 }
41+ newNodes = append (newNodes , w )
4342 } else {
4443 newWords = append (newWords , w )
4544 }
4645 }
4746
48- if isTransedEndWord || // 转换到了 endWord 说明已经找到了所有的最短路径
49- len (newWords ) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
47+ if len (newWords ) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
5048 len (newNodes ) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
5149 return
5250 }
@@ -59,38 +57,12 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
5957 nodes := []string {beginWord }
6058 bfs (words , nodes )
6159
62- res := [][]string {}
6360 if ! isTransedEndWord {
6461 // beginWord 无法 trans 到 endWord
65- return res
62+ return 0
6663 }
6764
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
9466}
9567
9668func deepCopy (src []string ) []string {
0 commit comments