【leetcode 回溯 C++】【剑指 Offer】 12. 矩阵中的路径

剑指 Offer 12. 矩阵中的路径

在这里插入图片描述

class Solution {
public:
    int N, M;
    bool dfs(vector<vector<char> >& board, string& word, int y, int x, int t) {
        if(t == word.size()) return true;
        if(x < 0 || x >= M || y < 0 || y >= N || board[y][x] != word[t]) return false;
        bool flag = false;
        int adds[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        char temp = board[y][x];
        board[y][x] = '#';
        for(auto add : adds) {
            int yt = y + add[0], xt = x + add[1];
            flag = flag || dfs(board, word, yt, xt, t + 1);
        }
        board[y][x] = temp;
        return flag;
    }
    bool exist(vector<vector<char>>& board, string word) {
        if(!word.size()) return true;
        N = board.size(), M = board[0].size();
        for(int ii = 0; ii < N; ii++) {
            for(int jj = 0; jj < M; jj++) {
                bool flag = dfs(board, word, ii, jj, 0);
                if(flag) return true;
            }
        }
        return false;
    }
};

在这里插入图片描述

class Solution {
public:
    int N, M;
    bool dfs(vector<vector<char> >& board, vector<vector<bool> >& visited, string word, int y, int x, int t) {
        if(t == word.size()) return true;
        if(x < 0 || x >= M || y < 0 || y >= N || visited[y][x] || board[y][x] != word[t]) return false;
        bool flag = false;
        int add[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        visited[y][x] = true;
        for(auto temp : add) {
            int yt = y + temp[0], xt = x + temp[1];
            flag = flag || dfs(board, visited, word, yt, xt, t + 1);
        }
        visited[y][x] = false;
        return flag;
    }
    bool exist(vector<vector<char>>& board, string word) {
        if(!word.size()) return true;
        N = board.size(), M = board[0].size();
        vector<vector<bool> > visited(N, vector(M, false));
        for(int ii = 0; ii < N; ii++) {
            for(int jj = 0; jj < M; jj++) {
                bool flag = dfs(board, visited, word, ii, jj, 0);
                if(flag) return true;
            }
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值