Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int m,n;
- int row[4]={1,-1,0,0};
- int col[4]={0,0,1,-1};
- public:
- vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
- m=mat.size(),n=mat[0].size();
- vector<vector<int>> res(m,vector<int>(n,-1));
- vector<vector<bool>> visited(m,vector<bool>(n,false));
- for(int i=0;i<m;i++){
- for(int j=0;j<n;j++){
- if(mat[i][j]==0){
- res[i][j]=0;
- continue;
- }
- visited[i][j]=true;
- res[i][j]=disFromNearestZero(mat,i,j,res,visited);
- visited[i][j]=false;
- }
- }
- return res;
- }
- int disFromNearestZero(vector<vector<int>>& mat,int i,int j,vector<vector<int>> &res,vector<vector<bool>> &visited){
- //base case
- if(mat[i][j]==0) return 0;
- int minDis=INT_MAX-1;
- for(int k=0;k<4;k++){
- int x=i+row[k],y=j+col[k];
- if(isValid(x,y) && !visited[x][y]){
- visited[x][y]=true;
- minDis=min(minDis, 1+disFromNearestZero(mat,x,y,res,visited));
- visited[x][y]=false;
- }
- }
- if(minDis==INT_MAX) return minDis-1;
- return minDis;
- }
- bool isValid(int i,int j){
- return i>=0 && j>=0 && i<m && j<n;
- }
- void print(vector<vector<int>> &res){
- for(auto &i:res){
- for(int j:i)
- cout<<j<<" ";
- cout<<"\n";
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement