212 Word Search II

1. Question

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, Givenwords=["oath","pea","eat","rain"]andboard=

[
  ['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 lettersa-z.

hint:

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.

2. Implementation

(1) Trie + Backtracking

class Solution {
    class TrieNode {
        char val;
        boolean isWord;
        TrieNode childNode[];

        public TrieNode() {
            childNode = new TrieNode[26];
        }
    }

    class Trie {
        TrieNode root;

        public Trie() {
            root = new TrieNode();
        }

        public void add(String word) {
            if (word == null || word.length() == 0) {
                return;
            }

            TrieNode curNode = root;

            for (char c : word.toCharArray()) {
                int index = c - 'a';

                if (curNode.childNode[index] == null) {
                    curNode.childNode[index] = new TrieNode();
                    curNode.val = c;
                }
                curNode = curNode.childNode[index];
            }
            curNode.isWord = true;
        }
    }

    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();

        if (board == null || board.length == 0 || words == null || words.length == 0) {
            return res;
        }

        Trie trie = new Trie();

        for (String word : words) {
            trie.add(word);
        }

        int m = board.length, n = board[0].length;
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        StringBuilder word = new StringBuilder();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                searchWord(i, j, trie.root, word, words, directions, board, res);
            }
        }
        return res;
    }

    public void searchWord(int row, int col, TrieNode node, StringBuilder word, String[] words, int[][] directions, char[][] board, List<String> res) {
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] == '#') {
            return;
        }

        char c = board[row][col];
        TrieNode curNode = node.childNode[c - 'a'];

        if (curNode == null) {
            return;
        }

        word.append(c);

        if (curNode.isWord) {
            curNode.isWord = false;
            res.add(word.toString());
        }

        board[row][col] = '#';

        for (int[] direction : directions) {
            int nextRow = row + direction[0];
            int nextCol = col + direction[1];
            searchWord(nextRow, nextCol, curNode, word, words, directions, board, res);
        }
        board[row][col] = c;
        word.setLength(word.length() - 1);
    }
}

3. Time & Space Complexity

时间复杂度O(kL) + O(mn * 4 ^ L), k是word的个数, L是每个word的平均长度, kl是建立trie的时间。我们的回溯算法对每个board的格子都遍历一遍,每个格子有4个方向可以走,知道走到word的长度为止,所以遍历的时间是mn * 4 ^ L,空间复杂度O(26*L) 主要是trie的空间

Last updated