|
| 1 | +type TrieNode struct { |
| 2 | + children map[byte]*TrieNode |
| 3 | + isWord bool |
| 4 | + refs int |
| 5 | +} |
| 6 | + |
| 7 | +func (this *TrieNode) addWord(word string) { |
| 8 | + cur := this |
| 9 | + cur.refs += 1 |
| 10 | + for c := 0; c < len(word); c++ { |
| 11 | + if _, ok := cur.children[word[c]]; !ok { |
| 12 | + cur.children[word[c]] = &TrieNode{children: make(map[byte]*TrieNode)} |
| 13 | + } |
| 14 | + cur = cur.children[word[c]] |
| 15 | + cur.refs += 1 |
| 16 | + } |
| 17 | + cur.isWord = true |
| 18 | +} |
| 19 | + |
| 20 | +func (this *TrieNode) removeWord(word string) { |
| 21 | + cur := this |
| 22 | + cur.refs += 1 |
| 23 | + for c := 0; c < len(word); c++ { |
| 24 | + if _, ok := cur.children[word[c]]; ok { |
| 25 | + cur = cur.children[word[c]]; |
| 26 | + cur.refs -= 1 |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func findWords(board [][]byte, words []string) []string { |
| 32 | + root := &TrieNode{children: make(map[byte]*TrieNode)} |
| 33 | + for _, w := range words { |
| 34 | + root.addWord(w); |
| 35 | + } |
| 36 | + |
| 37 | + ROWS, COLS := len(board), len(board[0]) |
| 38 | + res := make(map[string]bool) |
| 39 | + visit := make(map[int]bool) |
| 40 | + |
| 41 | + var dfs func(int, int, *TrieNode, string) |
| 42 | + dfs = func(r, c int, node *TrieNode, word string) { |
| 43 | + if |
| 44 | + r < 0 || r >= ROWS || |
| 45 | + c < 0 || c >= COLS || |
| 46 | + node.children[board[r][c]] == nil || |
| 47 | + node.children[board[r][c]].refs < 1 || |
| 48 | + visit[r*COLS + c] { |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + visit[r*COLS + c] = true |
| 53 | + node = node.children[board[r][c]] |
| 54 | + word += string(board[r][c]) |
| 55 | + if node.isWord { |
| 56 | + node.isWord = false |
| 57 | + res[word] = true |
| 58 | + root.removeWord(word) |
| 59 | + } |
| 60 | + |
| 61 | + dfs(r + 1, c, node, word) |
| 62 | + dfs(r - 1, c, node, word) |
| 63 | + dfs(r, c + 1, node, word) |
| 64 | + dfs(r, c - 1, node, word) |
| 65 | + visit[r*COLS + c] = false |
| 66 | + } |
| 67 | + |
| 68 | + for r := 0; r < ROWS; r++ { |
| 69 | + for c := 0; c < COLS; c++ { |
| 70 | + dfs(r, c, root, "") |
| 71 | + } |
| 72 | + } |
| 73 | + return list(res) |
| 74 | +} |
| 75 | + |
| 76 | +func list(mapping map[string]bool) []string { |
| 77 | + res := make([]string, 0, len(mapping)) |
| 78 | + for key, _ := range mapping { |
| 79 | + res = append(res, key) |
| 80 | + } |
| 81 | + return res |
| 82 | +} |
0 commit comments