LeetCode - Word Search II

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

 

Example 1:


Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2:


Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
 

Constraints:

m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique.

  

class TrieNode {
    String word;
    TrieNode[] children;
    
    public TrieNode () {
        word = null;
        children = new TrieNode[26]; 
    }
}
class Solution {
    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();
        // conrner case
        if (board == null || board[0] == null || words == null){
            return res;
        }
        // construct trie
        TrieNode root = new TrieNode();
        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;
        }
        // backtracking
       for (int row = 0; row < board.length; row++) {
           for (int column = 0; column < board[0].length; column++) {
               helper(board, root, row, column, res);
           }
        }
        return res;
    }
    public void helper(char[][] board, TrieNode parent, int r, int c, List<String> res) {
        // termination condition
        if(board[r][c] - 'a' < 0) {
            return;
        }
        TrieNode node = parent.children[board[r][c] - 'a'];
        
        if (node == null) {
            return;
        }
        if (node.word != null) {
            res.add(node.word);
            node.word = null;
        }
        char temp = board[r][c];
        board[r][c] = '#';
        //move up
        if ( r > 0 ) {
            helper(board, node, r - 1, c, res);
        }
        //move down
        if (r < board.length - 1) {
            helper(board, node, r + 1, c, res);
        }
        // move left
        if (c > 0) {
            helper(board, node, r, c - 1, res);
        }
        // move right
        if (c < board[0].length - 1) {
            helper(board, node, r, c + 1, res);
        }
        board[r][c] = temp;
    }
}

 

上一篇:字典树


下一篇:cf102012D. Rikka with Subsequences