212 Word Search II

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.

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.

分析& 代码

就是dfs+trie

1.先建立一个trie,把字典里所有的词加到trie里

2.对于板子里面的每个格子开始,向四个方向搜索,每次到了一个新的格子,添加在之前的单词上,然后检查trie,如果没有以这个开头的词,那就返回,如果包含了这个词,就加到结果里

要注意的是,即使包含这个词,还是要继续往下走,比如“aa”和“aab”都在词典中,不可以找到“aa”就停止了

代码

public class Solution {
    static final int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

    public List<String> findWords(char[][] board, String[] words) {
        Set<String> res = new HashSet<String>();
        Trie trie = new Trie();
        boolean[][] visited = new boolean[board.length][board[0].length];
        for(int i = 0; i < words.length; i++) {
            trie.insert(words[i]);
        }
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                dfs(res, board, "", i, j, trie, visited);
            }
        }
        return new ArrayList<String>(res);
    }

    private void dfs(Set<String> res, char[][] board, String word, int x, int y, Trie trie, boolean[][] visited) {
        if(x < 0 || y < 0 || x >= board.length || y >= board[0].length || visited[x][y]) {
            return;
        }
        word += board[x][y];
        if(!trie.startsWith(word)) {
            return;
        }
        if(trie.search(word)) {
            res.add(word);
        }
        visited[x][y] = true;
        for(int[] dir: dirs) {
            dfs(res, board, word, x + dir[0], y + dir[1], trie, visited);
        }
        visited[x][y] = false;
    }

    class TrieNode {
        char c;
        boolean isLeaf;
        TrieNode[] next;
        // Initialize your data structure here.
        public TrieNode() {
            next = new TrieNode[26];
            isLeaf = false;
        }
    }

    public class Trie {
        private TrieNode root;

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

        }

        // Inserts a word into the trie.
        public void insert(String word) {
            if(word == null || word.length() == 0) {
                return;
            }
            TrieNode cur = root;
            for(int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                int index = c - 'a';
                if(cur.next[index] == null) {
                    cur.next[index] = new TrieNode();
                    cur.next[index].c = c;
                }
                cur = cur.next[index];
            }
            cur.isLeaf = true;
        }

        // Returns if the word is in the trie.
        public boolean search(String word) {
            if(word == null || word.length() == 0) {
                return true;
            }
            TrieNode cur = root;
            for(int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                int index = c - 'a';
                if(cur.next[index] == null) {
                    return false;
                }
                cur = cur.next[index];
            }
            return cur.isLeaf;
        }

        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            if(prefix == null || prefix.length() == 0) {
                return true;
            }
            TrieNode cur = root;
            for(int i = 0; i < prefix.length(); i++) {
                char c = prefix.charAt(i);
                int index = c - 'a';
                if(cur.next[index] == null) {
                    return false;
                }
                cur = cur.next[index];
            }
            return true;
        }
    }      
}

results matching ""

    No results matching ""