Leetcode 1091:二进制矩阵中的最短路径

题目描述

在一个 N × N 的方形网格中,每个单元格有两种状态:空(0)或者阻塞(1)。

一条从左上角到右下角、长度为 k 的畅通路径,由满足下述条件的单元格 C_1, C_2, ..., C_k 组成:

相邻单元格 C_i 和 C_{i+1} 在八个方向之一上连通(此时,C_i 和 C_{i+1} 不同且共享边或角)
C_1 位于 (0, 0)(即,值为 grid[0][0])
C_k 位于 (N-1, N-1)(即,值为 grid[N-1][N-1])
如果 C_i 位于 (r, c),则 grid[r][c] 为空(即,grid[r][c] == 0)
返回这条从左上角到右下角的最短畅通路径的长度。如果不存在这样的路径,返回 -1 。

 

示例 1:

输入:[[0,1],[1,0]]

输出:2

示例 2:

输入:[[0,0,0],[1,1,0],[1,1,0]]

输出:4

 

提示:

1 <= grid.length == grid[0].length <= 100
grid[i][j] 为 0 或 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-path-in-binary-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

解题思路

class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
        int ans = 0,path = 0;
        if(grid.size() == 0 || grid[0].size() == 0) return 0;
        int row = grid.size(),col = grid[0].size();
        if(grid[0][0] == 1 || grid[row-1][col-1] == 1) return -1;
        queue<pair<int,int>> que;
        grid[0][0] = 1;
        que.push(make_pair(0,0));
        while(!que.empty()){
            int n = que.size();
            for(int i=0;i<n;i++){
                int x = que.front().first;
                int y = que.front().second;
                que.pop();
                for(int p=-1;p<=1;p++){
                    for(int q=-1;q<=1;q++){
                        int tx = x+p;
                        int ty = y+q;
                        if(tx>=0&&tx<row&&ty>=0&&ty<col&&grid[tx][ty]==0){
                            grid[tx][ty] = 1;
                            que.push(make_pair(tx,ty));
                        }
                        if(tx==row-1 && ty==col-1) return path+2;
                    }
                }
            }
            path++;
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值