矩阵中的路径

矩阵中的路径

http://www.nowcoder.com/questionTerminal/c61c6999eecb4b8f88a98f66b273a3cc

回溯法:

//
// Created by jt on 2020/9/18.
//
#include <vector>
using namespace std;

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        vector<vector<int> > visited(rows, vector<int>(cols, 0));
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (backtrace(matrix, rows, cols, str, visited, i, j, 0)) return true;
            }
        }
        return false;
    }

    bool backtrace(char *matrix, int rows, int cols, char *str, vector<vector<int> > &visited, int x, int y, int pos) {
        if (x < 0 || x >= rows || y < 0 || y >= cols) return false;
        if (visited[x][y] || matrix[x*cols + y] != str[pos]) return false;
        if (pos == strlen(str) - 1) return true;
        visited[x][y] = 1;
        // 上
        bool a = backtrace(matrix, rows, cols, str, visited, x - 1, y, pos+1);
        // 下
        bool b = backtrace(matrix, rows, cols, str, visited, x + 1, y, pos+1);
        // 左
        bool c = backtrace(matrix, rows, cols, str, visited, x, y - 1, pos+1);
        // 右
        bool d = backtrace(matrix, rows, cols, str, visited, x, y + 1, pos+1);
        visited[x][y] = 0;
        return a || b || c || d;
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 17:28
25届每天都在焦虑找工作的事情0offer情绪一直很低落硬撑着面了一个岗位岗位有应酬的成分面试的时候hr给我出各种场景题问的问题比较犀利&nbsp;有点压力面的感觉感觉有点回答不上来本来就压抑的情绪瞬间爆发了呢一瞬间特别想哭觉得自己特别没用没绷住掉眼泪了事后想想觉得自己挺有病的&nbsp;真的破大防了
喜欢唱跳rap小刺猬...:我觉得没关系吧,之前有一次面试leader给我压力面,我顶住了压力,结果入职的时候发现组里氛围很差,果断跑路。其实从面试就能大概看出组的情况,面试体验好的组倒是不一定好,但是面试体验不好的组。。。就很难说
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:02
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务