Skip to content

Commit 3e0328f

Browse files
aQuaaQua
authored andcommitted
126 ut fail
1 parent 59a53d3 commit 3e0328f

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

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

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
package Problem0126
22

3-
import (
4-
"fmt"
5-
)
6-
73
func findLadders(beginWord string, endWord string, words []string) [][]string {
84
res := [][]string{}
95
// 因为 beginWord 不能做 transformed word
@@ -12,9 +8,11 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
128

139
trans := map[string][]string{}
1410
isMatchedEndWord := false
11+
cnt := 1
1512
var bfs func([]string, []string)
1613

1714
bfs = func(words, nodes []string) {
15+
cnt++
1816
newWords := make([]string, 0, len(words))
1917
newNodes := make([]string, 0, len(words))
2018
for _, w := range words {
@@ -42,14 +40,41 @@ func findLadders(beginWord string, endWord string, words []string) [][]string {
4240
bfs(newWords, newNodes)
4341
}
4442

45-
nodes := make([]string, len(words)*2)
46-
nodes[0] = beginWord
43+
nodes := []string{beginWord}
4744
bfs(words, nodes)
4845

49-
fmt.Println(trans)
46+
if !isMatchedEndWord {
47+
return res
48+
}
49+
50+
var dfs func([]string, int)
51+
dfs = func(path []string, idx int) {
52+
if idx == cnt {
53+
if path[idx-1] == endWord {
54+
res = append(res, deepCopy(path))
55+
}
56+
return
57+
}
58+
59+
word := path[idx-1]
60+
for _, w := range trans[word] {
61+
path[idx] = w
62+
dfs(path, idx+1)
63+
}
64+
}
65+
path := make([]string, cnt)
66+
path[0] = beginWord
67+
dfs(path, 1)
68+
5069
return res
5170
}
5271

72+
func deepCopy(src []string) []string {
73+
temp := make([]string, len(src))
74+
copy(temp, src)
75+
return temp
76+
}
77+
5378
func deleteBeginWord(words []string, beginWord string) []string {
5479
i := 0
5580
for ; i < len(words); i++ {

0 commit comments

Comments
 (0)