今日算法12-矩阵中的路径

一、题目描述

题目链接:leetcode.cn/problems/ju...

难易程度:中等

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false

例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。

示例:

arduino 复制代码
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

二、解题思路

深度优先搜索(DFS)+ 剪枝

深度优先搜索: 可以理解为暴力法遍历矩阵中所有字符串可能性。DFS 通过递归,先朝一个方向搜到底,再回溯至上个节点,沿另一个方向搜索,以此类推。

剪枝: 在搜索中,遇到 这条路不可能和目标字符串匹配成功 的情况,则应立即返回,称之为 可行性剪枝 。

本题的输入是数组而不是矩阵(二维数组),因此需要先将数组转换成矩阵。

复杂度分析

时间复杂度 O(3K MN) : 最差情况下,需要遍历矩阵中长度为 K 字符串的所有方案,时间复杂度为 O(3K);矩阵中共有 MN 个起点,时间复杂度为 O(MN) 。

空间复杂度 O(K) : 搜索过程中的递归深度不超过 K ,因此系统因函数调用累计使用的栈空间占用 O(K) (因为函数返回后,系统调用的栈空间会释放)。最坏情况下 K=MN ,递归深度为 MN ,此时系统栈使用 O(MN) 的额外空间。

三、代码实现

ini 复制代码
class Solution {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int h = 0; h < board.length; h++) {
            for(int l = 0; l < board[0].length; l++) {
                if (dfs(board, words, h, l, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] words, int h, int l, int wordIndex) {
        if (h >= board.length || h < 0 
            || l >= board[0].length || l < 0 
            || board[h][l] != words[wordIndex]) {
            return false;
        }
        if (wordIndex == words.length - 1) return true;
        board[h][l] = '\0';
        boolean res = dfs(board, words, h + 1, l, wordIndex + 1) 
            || dfs(board, words, h - 1, l, wordIndex + 1) 
            || dfs(board, words, h, l + 1, wordIndex + 1) 
            || dfs(board, words, h , l - 1, wordIndex + 1);
        board[h][l] = words[wordIndex];
        return res;
    }
}

推荐阅读

封面

今日算法系列,题解更新地址:studeyang.tech/2023/0802.h...

相关推荐
一起养小猫17 小时前
LeetCode100天Day16-跳跃游戏II与H指数
算法·游戏
mit6.82417 小时前
两个有序集合|状态分析
算法
平生不喜凡桃李17 小时前
LeetCode 两数之和/三数之和
算法·leetcode·两数之和·三数之和
C雨后彩虹17 小时前
中文分词模拟器
java·数据结构·算法·华为·面试
BLi4ee17 小时前
【Scholarly Notes】Adaptive Model Pruning for Federated Learning
算法·机器学习·剪枝
Remember_99317 小时前
【LeetCode精选算法】二分查找专题二
java·数据结构·算法·leetcode·哈希算法
We་ct17 小时前
LeetCode 42. 接雨水:双指针解法深度剖析与全方法汇总
前端·算法·leetcode·typescript
液态不合群18 小时前
如何提升 C# 应用中的性能
开发语言·算法·c#
诗远Yolanda18 小时前
EI国际会议-通信技术、电子学与信号处理(CTESP 2026)
图像处理·人工智能·算法·计算机视觉·机器人·信息与通信·信号处理
程序员-King.18 小时前
day165—递归—最长回文子序列(LeetCode-516)
算法·leetcode·深度优先·递归