Advertisement
nikunjsoni

1293

May 10th, 2021
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestPath(vector<vector<int>>& grid, int k) {
  4.         int n = grid.size(), m = grid[0].size();
  5.         bool vis[n][m][k+1];
  6.         memset(vis, 0, sizeof(vis));
  7.        
  8.         queue<vector<int>> q;
  9.         q.push({0,0,0});
  10.         vis[0][0][0] = true;
  11.        
  12.         int dir[4][2] = {{-1,0}, {0,-1}, {0,1}, {1,0}};
  13.         int steps = 0;
  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.                 int curX = p[0], curY = p[1], curK = p[2];
  19.                 if(curX == n-1 && curY == m-1)
  20.                     return steps;
  21.                
  22.                 for(int j=0; j<4; j++){
  23.                     int nextX = curX+dir[j][0], nextY = curY+dir[j][1], nextK = curK;
  24.                     if(nextX < 0 || nextX >= n || nextY < 0 || nextY >=  m) continue;
  25.                     if(grid[nextX][nextY]) nextK++;
  26.                     if(nextK > k || vis[nextX][nextY][nextK]) continue;
  27.                     vis[nextX][nextY][nextK] = true;
  28.                     q.push({nextX, nextY, nextK});
  29.                 }
  30.             }
  31.             steps++;
  32.         }
  33.         return -1;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement