-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path212.Word-Search-II.go
100 lines (82 loc) · 1.85 KB
/
212.Word-Search-II.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// https://leetcode.com/problems/word-search-ii/
//
// algorithms
// Hard (28.27%)
// Total Accepted: 108,169
// Total Submissions: 382,655
// beats 81.01% of golang submissions
package leetcode
type TrieNode struct {
word string
children []*TrieNode
}
var res []string
var isVisited [][]bool
func findWords(board [][]byte, words []string) []string {
trieTree := buildTrieTree(words)
res = []string{}
row, col := len(board), len(board[0])
isVisited = make([][]bool, row)
for i := 0; i < row; i++ {
isVisited[i] = make([]bool, col)
}
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
isVisited[i][j] = true
recursive(board, i, j, trieTree)
isVisited[i][j] = false
}
}
return res
}
func recursive(board [][]byte, i, j int, node *TrieNode) {
row, col := len(board), len(board[0])
idx := (int)(board[i][j] - 'a')
if node.children[idx] == nil {
return
}
node = node.children[idx]
if node.word != "" {
res = append(res, node.word)
node.word = ""
}
if i > 0 && !isVisited[i-1][j] {
isVisited[i-1][j] = true
recursive(board, i-1, j, node)
isVisited[i-1][j] = false
}
if i < row-1 && !isVisited[i+1][j] {
isVisited[i+1][j] = true
recursive(board, i+1, j, node)
isVisited[i+1][j] = false
}
if j > 0 && !isVisited[i][j-1] {
isVisited[i][j-1] = true
recursive(board, i, j-1, node)
isVisited[i][j-1] = false
}
if j < col-1 && !isVisited[i][j+1] {
isVisited[i][j+1] = true
recursive(board, i, j+1, node)
isVisited[i][j+1] = false
}
}
func buildTrieTree(words []string) *TrieNode {
root := &TrieNode{
children: make([]*TrieNode, 26),
}
for _, w := range words {
tmp := root
for _, ch := range w {
idx := (int)(ch - 'a')
if tmp.children[idx] == nil {
tmp.children[idx] = &TrieNode{
children: make([]*TrieNode, 26),
}
}
tmp = tmp.children[idx]
}
tmp.word = w
}
return root
}