212. Word Search II - jiejackyzhang/leetcode-note GitHub Wiki
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.
For example,
Given words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return ["eat","oath"].
Note: You may assume that all inputs are consist of lowercase letters a-z.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
解题思路为backtracking+trie。
使用trie目的是为了减少backtracking的次数,如果当前元素不在所有words的prefix中,立即停止backtracking。
public class Solution {
    
    int[][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}};
    
    public class TrieNode {
        String word;
        TrieNode[] children = new TrieNode[26];
    }
    
    private TrieNode buildTrie(String[] words) {
        TrieNode root = new TrieNode();
        for(String word : words) {
            TrieNode node = root;
            for(char c : word.toCharArray()) {
                if(node.children[c-'a'] == null) {
                    node.children[c-'a'] = new TrieNode();
                }
                node = node.children[c-'a'];
            }
            node.word = word;
        }
        return root;
    }
    
    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();
        if(board == null || board.length == 0 || board[0].length == 0) return res;
        int m = board.length, n = board[0].length;
        TrieNode root = buildTrie(words);
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                dfs(board, i, j, root, res);
            }
        }
        return res;
    }
    
    private void dfs(char[][] board, int i, int j, TrieNode node, List<String> res) {
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return;
        char c = board[i][j];
        if(c == '#' || node.children[c-'a'] == null) return;
        node = node.children[c-'a'];
        if(node.word != null) {
            res.add(node.word);
            node.word = null; // avoid duplicate
        }
        board[i][j] = '#';
        for(int[] dir : dirs) {
            dfs(board, i+dir[0], j+dir[1], node, res);
        }
        board[i][j] = c;
    }
}