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;
    }


};
相关推荐
zyeyeye2 小时前
C++入门:从HelloWorld到命名空间揭秘
c语言·开发语言·c++·算法
牧羊人.3332 小时前
动手学深度学习 04 | Dataset 和 DataLoader、数据增强
人工智能·pytorch·深度学习·算法
elseif1233 小时前
【双指针/二分】P1102 A-B 数对
c++·算法·二分·双指针
电梯界知识分子3 小时前
江西抚州临川九尊府五层别墅:受限楼梯间里,全黑铝合金观光井道配曳引龙门架的落地记录
大数据·前端·网络·算法·家用电梯
木井巳3 小时前
【记忆化搜索】斐波那契数
java·算法·leetcode·深度优先·剪枝·推荐算法
落魄大学生之流水线上谋生计3 小时前
JVM内存结构、垃圾回收算法与类加载机制详解
jvm·算法
. . . . .3 小时前
comfyUI原理
人工智能·算法·机器学习
淡海水3 小时前
10-05-高级-模式匹配-CSharp如何改变与数据结构的交互方式
数据结构·算法·c#·模式匹配
果壳science3 小时前
张祥前统一场论研讨会在香港理工大学举办
人工智能·算法
桐盛科技3 小时前
能碳数据清洗用MAD算法,窗口大小和阈值怎么调?
物联网·算法·边缘计算