Skip to content

Instantly share code, notes, and snippets.

@zhuangh
Created February 13, 2018 18:58
Show Gist options
  • Save zhuangh/a8911fe917724334c911850ecdfeca88 to your computer and use it in GitHub Desktop.
Save zhuangh/a8911fe917724334c911850ecdfeca88 to your computer and use it in GitHub Desktop.
01 matrix DP
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = 0;
if( n > 0 ) m = matrix[0].size();
int max_dist = 100000;
vector< vector<int> > dist(n, vector<int> (m, max_dist));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!matrix[i][j]) dist[i][j] = 0;
else{
if(i > 0) dist[i][j] = min(dist[i-1][j]+1, dist[i][j]);
if(j > 0) dist[i][j] = min(dist[i][j-1]+1, dist[i][j]);
}
}
}
for(int i = n-1; i >= 0; i--){
for(int j = m-1; j >= 0; j--){
if(!matrix[i][j]) dist[i][j] = 0;
else{
if(i<n-1) dist[i][j] = min(dist[i+1][j]+1, dist[i][j]);
if(j<m-1) dist[i][j] = min(dist[i][j+1]+1, dist[i][j]);
}
}
}
return dist;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment