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

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/114397099