Skip to content

Commit 2288072

Browse files
authored
word search ii solution
1 parent 27bdf96 commit 2288072

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

word-search-ii/yhkee0404.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
func findWords(board [][]byte, words []string) []string {
2+
root := &TrieNode{}
3+
for _, w := range words {
4+
root.Insert(w)
5+
}
6+
7+
m, n := len(board), len(board[0])
8+
results := []string{}
9+
10+
var dfs func(r, c int, node *TrieNode)
11+
dfs = func(r, c int, node *TrieNode) {
12+
ch := board[r][c]
13+
if ch == '#' {
14+
return
15+
}
16+
idx := ch - 'a'
17+
next := node.children[idx]
18+
if next == nil {
19+
return
20+
}
21+
if next.word != "" {
22+
results = append(results, next.word)
23+
next.word = ""
24+
}
25+
26+
board[r][c] = '#'
27+
for _, d := range directions {
28+
nr, nc := r+d[0], c+d[1]
29+
if nr >= 0 && nr < m && nc >= 0 && nc < n {
30+
dfs(nr, nc, next)
31+
}
32+
}
33+
board[r][c] = ch
34+
}
35+
36+
for i := 0; i < m; i++ {
37+
for j := 0; j < n; j++ {
38+
dfs(i, j, root)
39+
}
40+
}
41+
42+
return results
43+
}
44+
45+
type TrieNode struct {
46+
children [26]*TrieNode
47+
word string
48+
}
49+
50+
func (t *TrieNode) Insert(word string) {
51+
node := t
52+
for _, ch := range word {
53+
idx := ch - 'a'
54+
if node.children[idx] == nil {
55+
node.children[idx] = &TrieNode{}
56+
}
57+
node = node.children[idx]
58+
}
59+
node.word = word
60+
}
61+
62+
var directions = [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}

0 commit comments

Comments
 (0)