|
| 1 | +package com.leetcode.array; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Deque; |
| 6 | + |
| 7 | +public final class ZeroOneMatrix { |
| 8 | + private ZeroOneMatrix() { |
| 9 | + } |
| 10 | + |
| 11 | + |
| 12 | + public static int[][] updateMatrix(int[][] mat) { |
| 13 | + return new Solver(mat).solve(); |
| 14 | + } |
| 15 | + |
| 16 | + private static final class Solver { |
| 17 | + private static final int[][] SHIFTS = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; |
| 18 | + private final int[][] mat; |
| 19 | + private final int m; |
| 20 | + private final int n; |
| 21 | + |
| 22 | + Solver(int[][] mat) { |
| 23 | + this.mat = mat; |
| 24 | + this.m = mat.length; |
| 25 | + this.n = mat[0].length; |
| 26 | + } |
| 27 | + |
| 28 | + private static int[][] initDist(int m, int n) { |
| 29 | + int[][] dist = new int[m][n]; |
| 30 | + for (int[] ints : dist) { |
| 31 | + Arrays.fill(ints, Integer.MAX_VALUE); |
| 32 | + } |
| 33 | + return dist; |
| 34 | + } |
| 35 | + |
| 36 | + int[][] solve() { |
| 37 | + int[][] dist = initDist(m, n); |
| 38 | + Deque<Integer> deque = new ArrayDeque<>(); |
| 39 | + for (int i = 0; i < m; i++) { |
| 40 | + for (int j = 0; j < n; j++) { |
| 41 | + if (mat[i][j] == 0) { |
| 42 | + deque.addFirst(i); |
| 43 | + deque.addFirst(j); |
| 44 | + dist[i][j] = 0; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + distBfs(dist, deque); |
| 49 | + return dist; |
| 50 | + } |
| 51 | + |
| 52 | + private void distBfs(int[][] dist, Deque<Integer> deque) { |
| 53 | + while (!deque.isEmpty()) { |
| 54 | + int curI = deque.removeLast(); |
| 55 | + int curJ = deque.removeLast(); |
| 56 | + for (int[] shift : SHIFTS) { |
| 57 | + int adjI = curI + shift[0]; |
| 58 | + int adjJ = curJ + shift[1]; |
| 59 | + if (isValid(adjI, adjJ) && dist[adjI][adjJ] > dist[curI][curJ] + 1) { |
| 60 | + dist[adjI][adjJ] = dist[curI][curJ] + 1; |
| 61 | + deque.addFirst(adjI); |
| 62 | + deque.addFirst(adjJ); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private boolean isValid(int i, int j) { |
| 69 | + return i > -1 && i < m && j > -1 && j < n; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments