knakul853

Untitled

Jun 9th, 2020
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
  4.        
  5.         if(matrix.empty()) return {{}};
  6.         int n = (int)matrix.size();
  7.         int m = (int)matrix[0].size();
  8.        
  9.         vector<vector<int>>ans(n, vector<int>(m, INT_MAX));
  10.           queue<pair<int,int>>q;
  11.        
  12.         int dx[4] = {1, -1, 0, 0};
  13.         int dy[4] = {0, 0, 1, -1};
  14.        
  15.         for ( int i=0;i<n;i++)
  16.         {
  17.             for(int j=0;j<m;j++)
  18.             {
  19.                 if(matrix[i][j] == 0){
  20.                     ans[i][j] = 0;
  21.                     q.push({i, j});
  22.                 }
  23.             }
  24.         }
  25.        
  26.        
  27.         while( !q.empty() )
  28.         {
  29.             auto node = q.front();
  30.             q.pop();
  31.            
  32.             int x = node.first;
  33.             int y = node.second;
  34.            
  35.             for(int i=0;i<4;i++)
  36.             {
  37.                 int nx = x + dx[i];
  38.                 int ny = y + dy[i];
  39.                
  40.                 if( nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
  41.                
  42.                 if(ans[nx][ny]==INT_MAX)
  43.                 {
  44.                     ans[nx][ny] = ans[x][y] + 1;
  45.                     q.push({nx, ny});
  46.                 }
  47.                
  48.             }
  49.         }
  50.        
  51.         return ans;
  52.        
  53.     }
  54. };
Add Comment
Please, Sign In to add comment