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

本文详细解析了LeetCode上的单词搜索II问题,通过字典树实现高效搜索矩阵中的所有可能单词组合,避免重复字母使用,并确保单词是字典中的有效词条。文章探讨了常见错误解决方案,如字母重复使用和单词遗漏问题,并提供了正确的递归深度优先搜索(DFS)算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<String> res = new ArrayList<>();
    public List<String> 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;i++){
            for(int j=0;j<board[0].length;j++){
                dfs(board,once,trie,i,j,"");
            }
        }

        return res;
    }

    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);
        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<word.length();i++){
                int index = word.charAt(i) - 'a';
                if(cur.children[index] != null) {
                    cur = cur.children[index];
                } else {
                    TrieNode child = new TrieNode();
                    cur.children[index] = child;
                    cur = child;
                }
            }
            cur.isLast = true;
        }

        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            return searchHelp(word, false);
        }

        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            return searchHelp(prefix, true);
        }

        private boolean searchHelp(String prefix, boolean isPrefix) {
            TrieNode cur = head;
            for(int i=0;i<prefix.length();i++){
                int index = prefix.charAt(i) - 'a';
                if(cur.children[index] !=null){
                    cur = cur.children[index];
                }else{
                    return false;
                }
            }
            if(isPrefix){
                return true;
            }else{
                return cur.isLast;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值