Word Search II


#1

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: 
words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

Output: ["eat","oath"]

Note:
You may assume that all inputs are consist of lowercase letters a-z.


#2

The below code uses a combination of Trie and DFS.

class Solution {
    TrieNode root = new TrieNode();
    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<>();
        buildTrie(words);
        TrieNode cur = root;
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                dfs(board, i, j, cur, result);
            }
        }
        
        return result;
        
    }
    
    int[][] cords = {{-1,0}, {1, 0}, {0, -1}, {0, 1}};
    public void dfs(char[][] board, int i, int j, TrieNode cur, List<String> result){
        char c = board[i][j];
        if(c=='#' || cur.children[c-'a']==null) return;
        cur = cur.children[c-'a'];
        if(cur.word!=null && cur.word!=""){
            result.add(cur.word);
            cur.word = null;
        }
        
        board[i][j] = '#';
        for(int[] cord : cords){
            int ni = i+cord[0], nj = j+cord[1];
            if(ni>=0 && nj>=0 && ni<= board.length-1 && nj<=board[0].length-1){
                dfs(board, ni, nj, cur, result);
            }
        }
        board[i][j] = c;
    }
    
    public void buildTrie(String[] words){
        for(String word : words){
            TrieNode cur = root;
            for(char c : word.toCharArray()){
                if(cur.children[c-'a']==null){
                    cur.children[c-'a'] = new TrieNode();
                }
                cur = cur.children[c-'a'];
            }
            cur.word = word;
        }
    }
    
    
    class TrieNode{
        String word;
        TrieNode[] children;
        TrieNode(){
            this.word="";
            this.children = new TrieNode[26];
        }
    }
    
}