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.

Solution:

public class Solution {
    public List<String> findWords(char[][] board, String[] words) {
        List<String> ans = new ArrayList<>();
        TrieNode tree = buildTire(words);
        int m = board.length;
        int n = board[0].length;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                helper(board, i, j, tree, ans);
        return ans;
    }
    public void helper(char[][] board, int i, int j, TrieNode cur, List<String> ans){
        char c = board[i][j];
        if(c=='.' || cur.next[c-'a']==null) return;
        cur = cur.next[c-'a'];
        if(cur.word!=null){
            ans.add(cur.word);
            cur.word = null;
        }
        board[i][j] = '.';
        int m = board.length;
        int n = board[0].length;
        if(i>0) helper(board, i-1, j, cur, ans);
        if(j>0) helper(board, i, j-1, cur, ans);
        if(i<m-1) helper(board, i+1, j, cur, ans);
        if(j<n-1) helper(board, i, j+1, cur, ans);
        board[i][j] = c;
    }
    public TrieNode buildTire(String[] words){
        TrieNode root = new TrieNode();
        for(String word : words){
            TrieNode cur = root;
            for(char c : word.toCharArray()){
                if(cur.next[c-'a']==null) cur.next[c-'a'] = new TrieNode();
                cur = cur.next[c-'a'];
            }
            cur.word = word;
        }
        return root;
    }
    class TrieNode{
        String word;
        TrieNode[] next = new TrieNode[26];
    }
}
comments powered by Disqus