Advertisement
nikunjsoni

1091

May 9th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
  4.         int n = grid.size(), m = grid[0].size(), steps = 1;
  5.         bool vis[n][m];
  6.         memset(vis, 0, sizeof vis);
  7.         if(n-1 == 0 && m-1 == 0) return 1;
  8.         if(grid[0][0]) return -1;
  9.         queue<pair<int, int>> q;
  10.         q.push({0,0});
  11.         vis[0][0] = true;
  12.        
  13.         int dir[8][2] = {{-1,0},{-1,-1},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};  
  14.         while(!q.empty()){
  15.             int sz = q.size();
  16.             for(int i=0; i<sz; i++){
  17.                 auto p = q.front(); q.pop();
  18.                 for(int k=0; k<8; k++){
  19.                     int nextX = p.first+dir[k][0], nextY=p.second+dir[k][1];
  20.                     if(nextX < 0 || nextX >= n || nextY < 0 || nextY >= m || vis[nextX][nextY] || grid[nextX][nextY]) continue;
  21.                     vis[nextX][nextY] = true;
  22.                     if(nextX == n-1 && nextY == m-1){
  23.                         return steps+1;
  24.                     }
  25.                     q.push({nextX, nextY});
  26.                 }
  27.             }
  28.             steps++;
  29.         }
  30.         return -1;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement