leetcode 127. 单词接龙

题解

bfs 思想,根据前面已经入队 queue 的单词 beginWord,然后把可以转换的单词 word 加入队列

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func ladderLength(beginWord string, endWord string, wordList []string) int {
res := 0
visited := make(map[int]bool)
queue := make([]string, 0)
queue = append(queue, beginWord)
for len(queue) > 0 {
res++
n := len(queue)
for i := 0; i < n; i++ {
beginWord := queue[0]
queue = queue[1:]
for j, word := range wordList {
if !visited[j] && canTransform(beginWord, word) {
if word == endWord {
return res + 1
}
visited[j] = true
queue = append(queue, word)
}
}
}
}
return 0
}

func canTransform(beginWord string, endWord string) bool {
n := len(beginWord)
for i := 0; i < n; i++ {
if beginWord[:i] + beginWord[i+1:] == endWord[:i] + endWord[i+1:] {
return true
}
}
return false
}