lintcode 787. The Maze 、788. The Maze II 、

787. The Maze

https://www.cnblogs.com/grandyang/p/6381458.html

与number of island不一样,递归的函数返回值是bool,不是void。

maze = -1用来表示已经访问的节点。

dp用来记录每个位置的是否能访问,如果dp != -1,就表示这个地方已经访问过了,可以避免多余的访问。

一直滑动用while循环来做,这里并没有没移动一次就增加一个访问。

int x = i,y = j必须这样写,因为之后的4种迭代都是从i、j这个位置出发,x、y在每一次迭代过程中已经发生了变化。

vector的初始化用{},如果是vector<vector<int>>,初始化用{{},{},{}}

class Solution {
public:
    /**
     * @param maze: the maze
     * @param start: the start
     * @param destination: the destination
     * @return: whether the ball could stop at the destination
     */
    bool hasPath(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination) {
        // write your code here
        int m = maze.size();
        if(m <= 0)
            return false;
        int n = maze[0].size();
        if(n <= 0)
            return false;
        vector<vector<int>> dp(m,vector<int>(n,-1));
        return hasPath(maze,dp,start[0],start[1],destination[0],destination[1]);
    }
    bool hasPath(vector<vector<int>>& maze,vector<vector<int>>& dp,int i,int j,int di,int dj){
        if(i == di && j == dj)
            return true;
        if(dp[i][j] != -1)
            return dp[i][j];
        maze[i][j] = -1;
        int m = maze.size(),n = maze[0].size();
        bool res = false;
        for(auto dir : dirs){
            int x = i,y = j;
            while(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] != 1){
                x += dir[0];
                y += dir[1];
            }
            x -= dir[0];
            y -= dir[1];
            if(maze[x][y] != -1)
                res |= hasPath(maze,dp,x,y,di,dj);
        }
        return res;
    }
    vector<vector<int>> dirs{{0,-1},{1,0},{0,1},{-1,0}};
};

 

788. The Maze II

 

转载于:https://www.cnblogs.com/ymjyqsx/p/10848694.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值