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


};
相关推荐
地平线开发者15 分钟前
BEVdet模型解析
算法·自动驾驶
tudousisi22228 分钟前
P2758 编辑距离 题解复盘
算法
粉色大象33 分钟前
考研线代重难点:二阶实对称矩阵合同快速判定|2008数二第8题真题精讲
线性代数·考研·矩阵
A_cainiao_A36 分钟前
【ggml系列】【第五篇】ggml_compute_forward_mul_mat 矩阵乘法算子源码与性能优化深度解析
线性代数·性能优化·矩阵
李可以量化40 分钟前
Tornado 从了解到精通(四)上:实战搭建 Web 应用与核心组件详解
算法
linux-hzh1 小时前
百日算法修炼 · Day 09
数据结构·算法·排序算法
DFT计算杂谈1 小时前
Janus单层Cr2SSe中的应变可调多压电效应与谷电子学
人工智能·算法·机器学习
今天AI了吗1 小时前
从 LLM 到 Agent Skill:把 AI 底层概念串起来
数据库·人工智能·sql·深度学习·神经网络·算法·机器学习
hanlin032 小时前
动态规划专练:力扣第1035、392题
算法·leetcode·动态规划
不正经学生2 小时前
C语言大小端字节序:内存里字节的排列顺序
c语言·开发语言·arm开发·c++·算法·c#