212 Word Search II

212
Word Search II
15.1%
Hard

dfs+trie
自定义一个简化版的trie,只需要add
dfs 比较 node.child 和 board[i][j]

public class Solution {
    int m,n;
    ArrayList rst;
    public List findWords(char[][] board, String[] words) {
        TrieNode trieRoot = new TrieNode();
        for (String word:words){
            addWordToTrie(trieRoot, word);
        }
        rst = new ArrayList();
        m = board.length;
        if (m==0) return rst;
        n = board[0].length;
        if (n==0) return rst;
        
        boolean[][] isVisited = new boolean[m][n];
        for (int i=0; i=m || x<0 || x>=n || isVisited[y][x]) return;
        int k = board[y][x] - 'a';
        if (node.child[k] == null) return;
        isVisited[y][x] = true;
        if (node.child[k].word != null) {
            rst.add(node.child[k].word);
            node.child[k].word = null;
        }
        dfs(board, isVisited, node.child[k], y, x+1);
        dfs(board, isVisited, node.child[k], y, x-1);
        dfs(board, isVisited, node.child[k], y+1, x);
        dfs(board, isVisited, node.child[k], y-1, x);
        isVisited[y][x] = false;
    }
    private void addWordToTrie(TrieNode root, String word){
        TrieNode p=root;
        for (int i=0; i

你可能感兴趣的:(212 Word Search II)