Sunday, July 16, 2017

212. 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.
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.



Solution:

We use a Trie to store all valid words.

Then use DFS to try if any word is valid in the board.



Code:


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