leetcode|212. Word Search II (字典树Trie && DFS)

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

https://leetcode.com/problems/word-search-ii/

Analysis

  1. 搜索问题,搜索矩阵中所有的单词组合,剪枝条件是如果当前单词没有匹配list的任一单词的前缀,则终止当前搜索。
  2. 如何快速判断剪枝条件呢?如果每次都遍历list中所有单词,效率太低。字典树是一种存储单词字典的数据结构。利用字典树可进行快速查询。

Wrong Solutions

  1. 一个字母使用多次
    corner case:
    [[“a”,“a”]]
    [“aaa”]
    action: 使用额外矩阵空间 boolean[][] once,记录访问过的字母。

  2. 遗漏一些匹配单词
    corner case:
    [[“a”,“b”,“c”],[“a”,“e”,“d”],[“a”,“f”,“g”]]
    [“abcdefg”,“gfedcbaaa”,“eaabcdgfa”,“befa”,“dgc”,“ade”]
    Output:
    [“abcdefg”,“befa”,“gfedcbaaa”]
    Expected:
    [“abcdefg”,“befa”,“eaabcdgfa”,“gfedcbaaa”]

思维误区:错误认为同一个递归树level上,看到的记录矩阵(boolean[][] once)是相同的,潜意识认为上下左右的几次dfs是并行执行的;但是其实他们是顺序执行的, dfs(board, once, trie, x+1, y, str);执行过后,可能会改变once;
之前一直纠结是否需要once[x][y]=false;

错误代码如下:

    void dfs(char[][] board, boolean[][] once, Trie trie, int x, int y, String str) {
        if(x<0||x>=board.length||y<0||y>=board[0].length||once[x][y]) return;
        str = str + board[x][y];
        if(!trie.startsWith(str)) return;
        if(trie.search(str)) {
            if(!res.contains(str)) res.add(str);
        }
        once[x][y]=true;
        dfs(board, once, trie, x+1, y, str);
        dfs(board, once, trie, x-1, y, str);
        dfs(board, once, trie, x, y+1, str);
        dfs(board, once, trie, x, y-1, str);
    }

Solution

    private final List res = new ArrayList<>();
    public List findWords(char[][] board, String[] words){
        res.clear();
        Trie trie = new Trie();
        for(String s:words){
            trie.insert(s);
        }
        boolean[][] once = new boolean[board.length][board[0].length];
        for(int i=0;i=board.length||y<0||y>=board[0].length||once[x][y]) return;
        str = str + board[x][y];
        if(!trie.startsWith(str)) return;
        if(trie.search(str)) {
            if(!res.contains(str)) res.add(str);
        }
        once[x][y]=true;
        dfs(board, once, trie, x+1, y, str);
        dfs(board, once, trie, x-1, y, str);
        dfs(board, once, trie, x, y+1, str);
        dfs(board, once, trie, x, y-1, str);
        once[x][y]=false;
    }

Trie

    private class TrieNode{
        private static final int CHILDREN_NUM = 26;
        private TrieNode[] children = new TrieNode[CHILDREN_NUM];
        private boolean isLast = false;
        TrieNode(){}
    }

    private class Trie {
        private TrieNode head;

        /** Initialize your data structure here. */
        public Trie() {
            head = new TrieNode();
        }

        /** Inserts a word into the trie. */
        public void insert(String word) {
            TrieNode cur = head;
            for(int i=0;i

你可能感兴趣的:(leetcode)