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 101 102 103 104 105
| func findWords(board [][]byte, words []string) []string { m := len(board) n := len(board[0]) res := make([]string, 0, len(words)) for i := 0; i < len(words); i++ { flag := false for j := 0; j < m; j++ { for k := 0; k < n; k++ { flag = dfs(board, words, j, k, i, 0) if flag { break } } if flag { break } } if flag { res = append(res, words[i]) } } return res }
var dirx = []int{-1, 1, 0, 0} var diry = []int{0, 0 ,-1, 1}
func dfs(board [][]byte, words []string, j, k, i, t int) bool { if board[j][k] != words[i][t] { return false } if t == len(words[i]) - 1 { return true } board[j][k] = ' ' defer func(j, k int, b byte) { board[j][k] = b } (j, k, words[i][t]) for d := 0; d < 4; d++ { newJ := j + dirx[d] newK := k + diry[d] if newJ >= 0 && newK >= 0 && newJ < len(board) && newK < len(board[0]) && board[newJ][newK] != ' ' { if dfs(board, words, newJ, newK, i, t + 1) { return true } } } return false }
type Trie struct { word string childrens [26]*Trie }
var dirx = []int{-1, 1, 0, 0} var diry = []int{0, 0, -1, 1}
func findWords(board [][]byte, words []string) []string { res := []string{} root := &Trie{} for _, v := range words { node := root for i := 0; i < len(v); i++ { if node.childrens[v[i] - 'a'] == nil { node.childrens[v[i] - 'a'] = &Trie{} } node = node.childrens[v[i] - 'a'] } node.word = v } var dfs func(x, y int, root *Trie) dfs = func(x, y int, root *Trie) { if x < 0 || y < 0 || x == len(board) || y == len(board[0]) { return } cur := board[x][y] if cur == ' ' || root.childrens[cur - 'a'] == nil { return } root = root.childrens[cur - 'a'] if root.word != "" { res = append(res, root.word) root.word = "" } board[x][y] = ' ' for p := 0; p < 4; p++ { dfs(x + dirx[p], y + diry[p], root) } board[x][y] = cur } for x := 0; x < len(board); x++ { for y := 0; y < len(board[0]); y++ { dfs(x, y, root) } } return res }
|