Leetcode - Word Search II
https://leetcode.com/problems/word-search-ii/
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] words =["oath","pea","eat","rain"]
Output:["eat","oath"]
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 | func findWords(board [][]byte, words []string) []string { if len(board) == 0 || len(board[0]) == 0 { return []string{} } root := buildTrie(words) result := []string{} for i := 0; i < len(board); i++ { for j := 0; j < len(board[0]); j++ { dfs(board, root, &result, i, j) } } return result } func dfs(board [][]byte, p *Trie, result *[]string, i, j int ) { if p == nil { return } directions := [][] int {{0, 1}, {0, -1}, {1, 0}, {-1, 0}} c := board[i][j] if c == '#' { return } p = p.Children[c - 'a' ] if p != nil && p.Val != "" { *result = append(*result, p.Val) p.Val = "" } board[i][j] = '#' for _, d := range directions { newx := i + d[0] newy := j + d[1] if newx >= 0 && newy >= 0 && newx < len(board) && newy < len(board[0]) { dfs(board, p, result, newx, newy) } } board[i][j] = c } type Trie struct { Val string Children []*Trie } func buildTrie(words []string) *Trie { root := &Trie{Children: make([]*Trie, 26)} for _, word := range words { node := root for i := 0; i < len(word); i++ { index := word[i] - 'a' if node.Children[index] == nil { node.Children[index] = &Trie{ Children: make([]*Trie, 26), } } node = node.Children[index] } node.Val = word } return root } func search(root *Trie, prefix []byte) *Trie { node := root for i := 0; i < len(prefix); i++ { index := prefix[i] - 'a' if node.Children[index] == nil { return nil } node = node.Children[index] } return node } func contains(arr []string, str string) bool { for _, s := range arr { if s == str { return true } } return false } |