nikunjsoni

317

May 2nd, 2021
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestDistance(vector<vector<int>>& grid) {
  4.         int rows = grid.size(), cols = grid[0].size();
  5.         int ans = INT_MAX;
  6.         int total[rows][cols];
  7.         memset(total, 0, sizeof total);
  8.        
  9.         int itr = 0;
  10.         int dir[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
  11.         for(int i=0; i<rows; i++)
  12.             for(int j=0; j<cols; j++){
  13.                 if(grid[i][j] == 1){
  14.                     int currMin = INT_MAX;
  15.                     queue<pair<int, int>> q;
  16.                     q.push({i, j});
  17.                     auto dist = grid;
  18.                     while(!q.empty()){
  19.                         auto p = q.front(); q.pop();
  20.                         for(int k=0; k<4; k++){
  21.                             int nextX = p.first+dir[k][0], nextY = p.second+dir[k][1];
  22.                             if(nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || grid[nextX][nextY] != itr)
  23.                                 continue;
  24.                             dist[nextX][nextY] = dist[p.first][p.second]+1;
  25.                             total[nextX][nextY] += dist[nextX][nextY]-1;
  26.                             grid[nextX][nextY]--;
  27.                             q.push({nextX, nextY});
  28.                             currMin = min(currMin, total[nextX][nextY]);
  29.                         }
  30.                     }
  31.                     itr--;
  32.                     ans = currMin;
  33.                 }
  34.             }
  35.        
  36.         return (ans==INT_MAX) ? -1 : ans;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment