leetcode-回溯法-矩阵中的路径

https://www.nowcoder.com/practice/c61c6999eecb4b8f88a98f66b273a3cc?tpId=13&tqId=11218&tPage=4&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/description/

cpp 复制代码
class Solution {
  public:

    bool hasPath(char* matrix, int rows, int cols, char* str, int path_len, int i,
                 int j, vector<vector<bool>>& visited) {
        if (str[path_len] == '\0') {
            return true;
        }
        if (i < 0 || i >= rows || j < 0 || j >= cols || visited[i][j] ||
                matrix[i * cols + j] != str[path_len]) {
            return false;
        }
        visited[i][j] = true;
        path_len++;
        bool res =  hasPath(matrix, rows, cols, str, path_len, i + 1, j, visited) ||
                    hasPath(matrix, rows, cols, str, path_len, i - 1, j, visited) ||
                    hasPath(matrix, rows, cols, str, path_len, i, j + 1, visited) ||
                    hasPath(matrix, rows, cols, str, path_len, i, j - 1, visited);

        if (!res) {
            visited[i][j] = false;
            path_len--;
        }
        
        /* 注意,不加上面条件也可以,可以这么理解,如果是true,就直接返回了。
        visited[i][j] = false;
        path_len--;
		*/
        return res;
    }
    bool hasPath(char* matrix, int rows, int cols, char* str) {
        // 11:10
        vector<vector<bool>> visited(rows, vector<bool>(cols, false));
        int path_len = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                bool res = hasPath(matrix, rows, cols, str, path_len, i, j, visited);
                if (res) {
                    return true;
                }
            }
        }
        return false;
    }


};
相关推荐
re林檎几秒前
算法札记——5.15
算法
鱼子星_5 分钟前
【数据结构与算法】OJ题目详解(一)-单链表:从易到难的面试OJ题目
c语言·数据结构·算法·链表·面试·职场和发展
人道领域6 分钟前
【LeetCode刷题日记】递归与回溯实战 257.二叉树的所有路径——一篇文章彻底搞懂回溯
开发语言·python·算法·leetcode
ulias2128 分钟前
leetcode热题 - 7
数据结构·算法·leetcode
吃好睡好便好9 分钟前
在Matlab中用sphere( )函数绘制球面图
开发语言·前端·javascript·学习·算法·matlab·信息可视化
图码10 分钟前
矩阵中的“对角线强迫症”:如何优雅地判断Toeplitz矩阵?
数据结构·c++·线性代数·算法·青少年编程·矩阵
lynnlovemin11 分钟前
二分查找与二分答案算法详解(基于C++实现)
c语言·开发语言·算法·二分查找·二分答案
瑞行AI13 分钟前
一套数据格式框架搞定大模型微调和对齐训练
算法·语言模型
玛卡巴卡ldf14 分钟前
【LeetCode 手撕算法】(动态规划)爬楼梯、杨辉三角、打家劫舍、完全平方数、零钱兑换、单词拆分、最长递增子序列、乘积最大子数组、分割等和子集
java·数据结构·算法·leetcode·动态规划·力扣
jake·tang15 分钟前
深度解析 VESC 参数辨识源码:电阻、电感与磁链
arm开发·c++·嵌入式硬件·算法·数学建模·傅立叶分析