剑指offer--矩阵中的路径

力扣 79

思路:
DFS + 回溯
代码:

#include
using namespace std;
int directs[4][2] ={{1,0},{-1,0},{0,-1},{0,1}};
class Solution{
public:
    bool dfs(vector<vector<char>>& board,string& word,vector<vector<bool>>& visited,int x,int y,int depth){
        if(word[depth] != board[x][y]){
            return false;
        }
        if(depth == word.size()-1){
            return true;
        }
        visited[x][y] = true;
        for(int i = 0;i<4;++i){
            int nextX = x +directs[i][0];
            int nextY = y +directs[i][1];
            if(nextX >= 0 && nextY >= 0 && nextX < board.size() && nextY < board[0].size() && !visited[nextX][nextY]){
                if(dfs(board,word,visited,nextX,nextY,depth+1)){
                    return true;
                }
            }
        }
        visited[x][y] = false;
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        if(word == ""){
            return true;
        }
        int rows = board.size();
        int cols = board[0].size();
        if(rows == 0){
            return false;
        }
        vector<vector<bool>> visited(rows,vector<bool>(cols,false));
        for(int i = 0;i<rows;++i){
            for(int j = 0;j < cols;++j){
                visited[i][j] = true;
                if(dfs(board,word,visited,i,j,0)){
                    return true;
                }
                visited[i][j] = false;
            }
        }
        return false;
    }
};

你可能感兴趣的:(力扣算法题)