forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
67 lines (63 loc) · 1.2 KB
/
Solution.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
func findWords(board [][]byte, words []string) []string {
counter := make([]int, 26)
for _, b := range board {
for _, c := range b {
counter[c-'a']++
}
}
s := make(map[string]bool)
for _, word := range words {
s[word] = true
}
check := func(word string) bool {
cnt := make([]int, 26)
for i := range word {
cnt[word[i]-'a']++
}
for i := 0; i < 26; i++ {
if counter[i] < cnt[i] {
return false
}
}
return true
}
var dfs func(i, j, l int, word string) bool
dfs = func(i, j, l int, word string) bool {
if l == len(word) {
return true
}
if i < 0 || i >= len(board) || j < 0 || j >= len(board[0]) || board[i][j] != word[l] {
return false
}
c := board[i][j]
board[i][j] = '0'
ans := false
dirs := []int{-1, 0, 1, 0, -1}
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
ans = ans || dfs(x, y, l+1, word)
}
board[i][j] = c
return ans
}
find := func(word string) bool {
if !check(word) {
return false
}
for i, b := range board {
for j, _ := range b {
if dfs(i, j, 0, word) {
return true
}
}
}
return false
}
var ans []string
for word, _ := range s {
if find(word) {
ans = append(ans, word)
}
}
return ans
}