1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public int[][] updateMatrix(int[][] mat) { int[][] result = new int[mat.length][mat[0].length]; initialize(result); for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[0].length; j++) { helper(mat, result, i, j); } } return result; }
private void initialize(int[][] result) { for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { result[i][j] = -1; } } }
private int helper(int[][] mat, int[][] result, int row, int col) { if (isOutOfBound(mat, row, col) || result[row][col] == -2) { return Integer.MAX_VALUE; } if (result[row][col] == -1 && mat[row][col] == 0) { result[row][col] = 0; return result[row][col]; } if (result[row][col] != -1) return result[row][col];
result[row][col] = -2; int up = helper(mat, result, row - 1, col); int down = helper(mat, result, row + 1, col); int left = helper(mat, result, row, col - 1); int right = helper(mat, result, row, col + 1); int minimum = Math.min(Math.min(left, right), Math.min(up, down)) + 1; result[row][col] = minimum; return result[row][col]; }
private boolean isOutOfBound(int[][] mat, int row, int col) { return row < 0 || row >= mat.length || col < 0 || col >= mat[0].length; } }
|