-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0127_word_ladder.go
51 lines (46 loc) · 1.03 KB
/
0127_word_ladder.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
func ladderLength(beginWord string, endWord string, wordList []string) int {
wordMap := getWordMap(wordList, beginWord)
que := []string{beginWord}
depth := 0
for len(que) > 0 {
depth++
qlen := len(que)
for i := 0; i < qlen; i++ {
word := que[0]
que = que[1:]
candidates := getCandidates(word)
for _, candidate := range candidates {
if _, ok := wordMap[candidate]; ok {
if candidate == endWord {
return depth + 1
}
delete(wordMap, candidate)
que = append(que, candidate)
}
}
}
}
return 0
}
func getWordMap(wordList []string, beginWord string) map[string]int {
wordMap := make(map[string]int)
for i, word := range wordList {
if _, ok := wordMap[word]; !ok {
if word != beginWord {
wordMap[word] = i
}
}
}
return wordMap
}
func getCandidates(word string) []string {
var res []string
for i := 0; i < 26; i++ {
for j := 0; j < len(word); j++ {
if word[j] != byte(int('a')+i) {
res = append(res, word[:j]+string(int('a')+i)+word[j+1:])
}
}
}
return res
}