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


};
相关推荐
课堂剪切板34 分钟前
ch07 题解
算法·深度优先
科大饭桶2 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
我爱C编程4 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7894 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
chao_7894 小时前
Selenium 自动化实战技巧【selenium】
自动化测试·selenium·算法·自动化
YuTaoShao4 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
怀旧,4 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
泛舟起晶浪4 小时前
相对成功与相对失败--dp
算法·动态规划·图论
地平线开发者5 小时前
地平线走进武汉理工,共建智能驾驶繁荣生态
算法·自动驾驶
IRevers6 小时前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶