Day 33–01 Matrix (Medium)

class Solution {
public int[][] updateMatrix(int[][] matrix) {

if(matrix == null
|| matrix.length == 0
|| matrix[0].length == 0)
return matrix;
int m = matrix.length;
int n = matrix[0].length;
int[][] dist = new int[m][n];
for(int[] a : dist) {
Arrays.fill(a, 10001);
}
for(int i = 0; i < m; i++) {
for(int j = 0; j< n; j++) {
if(matrix[i][j] == 0) {
dist[i][j] = 0;
} else {
if(i > 0) {
dist[i][j] =
Math.min(dist[i-1][j] + 1,
dist[i][j]);
}
if(j > 0) {
dist[i][j] =
Math.min(dist[i][j-1] + 1,
dist[i][j]);
}
}
}
}

for(int i = m-1; i >= 0; i--) {
for(int j = n-1; j >= 0; j--) {
if(i < m-1) {
dist[i][j] =
Math.min(dist[i+1][j] + 1,
dist[i][j]);
}
if(j < n-1){
dist[i][j] =
Math.min(dist[i][j+1] + 1,
dist[i][j]);
}
}
}
return dist;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store