Skip to content

Commit

Permalink
127 ut fail
Browse files Browse the repository at this point in the history
  • Loading branch information
aQua authored and aQua committed Sep 15, 2017
1 parent c58fbcc commit 4b921bf
Showing 1 changed file with 8 additions and 36 deletions.
44 changes: 8 additions & 36 deletions Algorithms/0127.word-ladder/word-ladder.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
package Problem0127

func ladderLength(beginWord string, endWord string, wordList []string) int {
func ladderLength(beginWord string, endWord string, words []string) int {
// 因为 beginWord 不能做 transformed word
// 先删掉 words 中的 beginWord,
// 可以让后面的 trans 少很多的断头 path,会加快程序。
// 也更符合题意
// 删除下面这句,程序也能 accepted,但是会从 269ms 减慢到 319ms
words = deleteBeginWord(words, beginWord)

// trans 用来查找 k->?
trans := map[string][]string{}
// isTransedEndWord 用于在生成 trans 的过程中标记,存在 ->endWord 的转换关系
// 用于提前结束
isTransedEndWord := false
// cnt 用于记录生成trans的迭代次数
// 其实也是最短路径的长度
// TODO: 修改 cnt 为 res
cnt := 1
var bfs func([]string, []string)
// 使用 bfs 方法,递归地生成 trans
Expand All @@ -30,23 +29,22 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
isTransed := false
for _, n := range nodes {
if isTransable(n, w) {
trans[n] = append(trans[n], w)
isTransed = true
break
}
}

if isTransed {
newNodes = append(newNodes, w)
if w == endWord {
isTransedEndWord = true
return
}
newNodes = append(newNodes, w)
} else {
newWords = append(newWords, w)
}
}

if isTransedEndWord || // 转换到了 endWord 说明已经找到了所有的最短路径
len(newWords) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
if len(newWords) == 0 || // words 的所有单词都已经可以从 beginWord trans 到
len(newNodes) == 0 { // newWords 中单词,是 beginWord 无法 trans 到的
return
}
Expand All @@ -59,38 +57,12 @@ func ladderLength(beginWord string, endWord string, wordList []string) int {
nodes := []string{beginWord}
bfs(words, nodes)

res := [][]string{}
if !isTransedEndWord {
// beginWord 无法 trans 到 endWord
return res
return 0
}

path := make([]string, cnt)
path[0] = beginWord

var dfs func(int)
// 使用 dfs 方法,生成最短路径
dfs = func(idx int) {
if idx == cnt {
// path 已经填充完毕
if path[idx-1] == endWord {
// 最后一个单词是 endWord,说明这是一条最短路径
res = append(res, deepCopy(path))
}
return
}

prev := path[idx-1]
for _, w := range trans[prev] {
// 利用 prev->w 填充 path[idx]
path[idx] = w
dfs(idx + 1)
}
}

dfs(1)

return res
return cnt
}

func deepCopy(src []string) []string {
Expand Down

0 comments on commit 4b921bf

Please sign in to comment.