Advertisement
nikunjsoni

1162

May 2nd, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int maxDistance(vector<vector<int>>& g, int steps = 0) {
  4.         queue<pair<int, int>> q, q1;
  5.        
  6.         for(int i = 0; i < g.size(); ++i)
  7.             for(int j = 0; j < g[i].size(); ++j)
  8.                 if(g[i][j] == 1)
  9.                     q.push({ i - 1, j }), q.push({ i + 1, j }), q.push({ i, j - 1 }), q.push({ i, j + 1 });
  10.        
  11.         while(!q.empty()) {
  12.             ++steps;
  13.             while(!q.empty()){
  14.                 int i = q.front().first, j = q.front().second;
  15.                 q.pop();
  16.                 if(i >= 0 && j >= 0 && i < g.size() && j < g[i].size() && g[i][j] == 0) {
  17.                     g[i][j] = steps;
  18.                     q1.push({ i - 1, j }), q1.push({ i + 1, j }), q1.push({ i, j - 1 }), q1.push({ i, j + 1 });
  19.                 }
  20.             }
  21.             swap(q1, q);
  22.         }
  23.        
  24.         return steps == 1 ? -1 : steps - 1;
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement