Leetcode - Word Search II
violet
posted @ Mar 27, 2020 10:51:31 AM
in 算法
with tags
Algorithm Trie Golang backtracking
, 365 阅读
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"]
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 }