1091. Shortest Path in Binary Matrix

In an N by N square grid, each cell is either empty (0) or blocked (1).

A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, …, C_k such that:

Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
C_1 is at location (0, 0) (ie. has value grid[0][0])
C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
题意:找最短的路径,55的迷宫做过,2020的迷宫考过,今天遇到这道题,无脑DFS。我太菜了,这是送分题啊!
BFS AC代码(44ms):

class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
        queue<pair<int,int>> q;
        int dir[8][2] = {
            {-1,-1},{-1,0},{-1,1},
            {0,-1},{0,1},
            {1,-1},{1,0},{1,1}
        };
        int n = grid.size();
        int res=0;
        if(grid[0][0]||grid[n-1][n-1]) return -1;
        q.push(make_pair(0,0));
        while(!q.empty()){
            int m = q.size();res++;
            for(int j=0;j<m;j++){
            pair<int,int> tmp = q.front();
            q.pop();
            int r = tmp.first,c = tmp.second;
            for(int i=0;i<8;i++){
                int r0 = r+dir[i][0],c0 = c + dir[i][1];
                if(r0<0||r0==n||c0<0||c0==n||grid[r0][c0])  continue;
                if(r0==n-1&&c0==n-1)    return res+1;
                q.push(make_pair(r0,c0));
                grid[r0][c0] = 1;
            }
            }
        }
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/Csdn_jey/article/details/92390205