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


};
相关推荐
@我漫长的孤独流浪3 分钟前
数据结构测试模拟题(4)
数据结构·c++·算法
智驱力人工智能6 分钟前
智慧零售管理中的客流统计与属性分析
人工智能·算法·边缘计算·零售·智慧零售·聚众识别·人员计数
SY师弟20 分钟前
51单片机基础部分——矩阵按键检测
嵌入式硬件·矩阵·51单片机
Yxh181377845541 小时前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
WindSearcher1 小时前
大模型微调相关知识
后端·算法
取酒鱼食--【余九】1 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar
Magnum Lehar3 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
水蓝烟雨3 小时前
[面试精选] 0094. 二叉树的中序遍历
算法·面试精选
超闻逸事3 小时前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解4 小时前
C++类和对象(上)
开发语言·c++·算法