Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.    
  5.     bool validPosition(int x, int y, int n, int m, vector<vector<int>>& grid){
  6.         if(x < 0 or x >= n or y < 0 or y >= m) return false;
  7.         return grid[x][y] == 0;
  8.     }
  9.    
  10.     struct coord{
  11.         int x, y;
  12.         coord(int _x, int _y){
  13.             x = _x;
  14.             y = _y;
  15.         }
  16.     };
  17.    
  18.    
  19.     int shortestPathBinaryMatrixUtil(vector<vector<int>>& grid){
  20.        
  21.         if(grid.empty() or grid[0][0] == 1) return -1;
  22.        
  23.         int n = grid.size();
  24.         int m = grid[0].size();
  25.        
  26.         vector<vector<int>> dist(n, vector<int>(m, INT_MAX - 1));
  27.         dist[0][0] = 0;
  28.        
  29.         queue<coord> bfsQ;
  30.         bfsQ.push(coord(0,0));
  31.        
  32.        
  33.         while(bfsQ.empty() == false){
  34.             coord currPoint = bfsQ.front();
  35.             bfsQ.pop();
  36.             for(int dx = -1; dx <= 1; dx++){
  37.                 for(int dy = -1; dy <= 1; dy++){
  38.                     if(dx == 0 and dy == 0) continue;
  39.                     int newX = currPoint.x + dx;
  40.                     int newY = currPoint.y + dy;
  41.                     if(validPosition(newX, newY, n, m, grid)){
  42.                         if(dist[currPoint.x][currPoint.y] + 1 < dist[newX][newY]){
  43.                             dist[newX][newY] = dist[currPoint.x][currPoint.y] + 1;
  44.                             bfsQ.push(coord(newX, newY));
  45.                         }
  46.                     }
  47.                 }
  48.             }
  49.         }
  50.        
  51.         return dist[n - 1][m - 1] == (INT_MAX - 1) ? -1: dist[n - 1][m - 1] + 1;
  52.     }
  53.    
  54.    
  55.     int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
  56.         int shortestPath = shortestPathBinaryMatrixUtil(grid);
  57.         return shortestPath;
  58.     }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement