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_l 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])
the If C_i IS located block AT (R & lt, C), the then Grid [R & lt] [C] empty IS (IE Grid [R & lt] [C] == 0.).
the return The length of path from The Shortest SUCH Clear Top-left to bottom-right the If Not SUCH A path does exist, return -1..
meaning of problems: to find the shortest path, 5 labyrinth done 5, 20 maze test 20 too, encountered this question today, no brain DFS. I was too dishes, it is sent to sub-title ah!
BFS AC Code (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;
    }
};

Guess you like

Origin blog.csdn.net/Csdn_jey/article/details/92390205
Recommended