专栏名称: 程序IT圈
一个学习编程技术和读者福利共存的公众号,每天推送高质量的优秀博文和原创文章,开源项目,实用工具,面试技巧等 。公众号每月至少一次读者送书福利! 关注置顶,不错过精彩推送!
目录
相关文章推荐
OSC开源社区  ·  萨姆·奥特曼:OpenAI在开源问题上一直处 ... ·  4 天前  
OSC开源社区  ·  三位全球顶尖专家解码DeepSeek崛起与开源革命 ·  5 天前  
程序员小灰  ·  我们正处于时代的拐点 ·  5 天前  
程序员小灰  ·  DeepSeek遭暴力破解,攻击IP均来自美国! ·  1 周前  
51好读  ›  专栏  ›  程序IT圈

​LeetCode刷题实战212:单词搜索 II

程序IT圈  · 公众号  · 程序员  · 2021-03-16 13:52

正文

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 单词搜索 II,我们先来看题面:
https://leetcode-cn.com/problems/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.

题意


给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

示例


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

输出:["eat","oath"]

提示:

m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] 是一个小写英文字母
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] 由小写英文字母组成
words 中的所有字符串互不相同


解题

方法:前缀树+深度优先搜索。


public class Solution {
    private TrieNode root = new TrieNode();
    private int[] ro = {-1, 1, 0, 0};
    private int[] co = {0, 0, -1, 1};
    private void find(char[][] board, boolean[][] visited, int row, int col, TrieNode node, Set founded) {
        visited[row][col] = true;
        TrieNode current = node.nexts[board[row][col]-'a'];
        if (current.word != null) founded.add(current.word);
        for(int i=0; i<4; i++) {
            int nr = row + ro[i];
            int nc = col + co[i];
            if (nr < 0 || nr >= board.length || nc < 0 || nc >= board[nr].length || visited[nr][nc]) continue;
            TrieNode next = current.nexts[board[nr][nc]-'a'];
            if (next != null) find(board, visited, nr, nc, current, founded);
        }
        visited[row][col] = false;
    }
    public List findWords(char[][] board, String[] words) {
        Set founded = new HashSet<>();
        for(int i=0; i            char[] wa = words[i].toCharArray();
            TrieNode node = root;
            for(int j=0; j            node.word = words[i];
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for(int i=0; i            for(int j=0; j                if (root.nexts[board[i][j]-'a'] != null) find(board, visited, i, j, root, founded);
            }
        }
        List results = new ArrayList<>();
        results.addAll(founded);
        return results;
    }
}
class TrieNode {
    String word;
    TrieNode[] nexts = new TrieNode[26];
    TrieNode append(char





请到「今天看啥」查看全文