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++){
- visited[i][j]=true;
- 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(res[i][j] != -1) return res[i][j];
- if(mat[i][j]==0) {res[i][j]=0;return 0;}
- int minDis=INT_MAX;
- 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;
- }
- }
- res[i][j]=minDis;
- return minDis;
- }
- bool isValid(int i,int j){
- return i>=0 && j>=0 && i<m && j<n;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement