542 01 Matrix

class Solution {
    public int[][] updateMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0) return new int[0][0];
        int n = matrix.length, m = matrix[0].length;
        int[][] dist = new int[n][m];
        Queue<int[]> q = new LinkedList<>();

        for (int[] row : dist){
            Arrays.fill(row, Integer.MAX_VALUE);
        }

        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (matrix[i][j] == 0){
                    dist[i][j] = 0;
                    q.offer(new int[]{i, j});
                }
            }
        }

        int[] x_moves = {0, 1, 0, -1};
        int[] y_moves = {1, 0, -1, 0};

        while (!q.isEmpty()){
            int size = q.size();

            for (int i = 0; i < size; i++){
                int[] cur = q.poll();

                for (int k = 0; k < 4; k++){
                    int xx = cur[0] + x_moves[k];
                    int yy = cur[1] + y_moves[k];

                    if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;

                    if (dist[cur[0]][cur[1]] + 1 < dist[xx][yy]){
                        dist[xx][yy] = dist[cur[0]][cur[1]] + 1;
                        q.offer(new int[]{xx, yy});
                    }
                }
            }
        }

        return dist;
    }
}

results matching ""

    No results matching ""