【搜索】542. 01 Matrix(多源 bfs / 线性dp)

一、题目描述

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Input:
[[0,0,0],
[0,1,0],
[1,1,1]]

Output:
[[0,0,0],
[0,1,0],
[1,2,1]]

Note:

  • The number of elements of the given matrix will not exceed 10,000.
    There are at least one 0 in the given matrix.
    The cells are adjacent in only four directions: up, down, left and right.

二、题解

方法一:多源 bfs

final static int[][] dir = { {0,1},{0,-1},{1,0},{-1,0} };
public int[][] updateMatrix(int[][] matrix) {
    int R = matrix.length, C = matrix[0].length;
    Queue<int[]> q = new ArrayDeque<>();
    boolean[][] vis = new boolean[R][C];
    for (int i = 0; i < R; i++) 
    for (int j = 0; j < C; j++) {
        if (matrix[i][j] == 0) {
            q.add(new int[] {i, j});
            vis[i][j] = true;
        }
    } 
    while (!q.isEmpty()) {
        int[] now = q.poll();
        for (int k = 0; k < 4; k++) {
            int tx = now[0] + dir[k][0];
            int ty = now[1] + dir[k][1];
            if (tx >= 0 && tx < R && ty >= 0 && ty < C && !vis[tx][ty]) {
                q.add(new int[] {tx, ty});
                matrix[tx][ty] = matrix[now[0]][now[1]] + 1;
                vis[tx][ty] = true;
            }
        }
    }
    return matrix;
}

复杂度分析

  • 时间复杂度: O ( R × C ) O(R × C)
  • 空间复杂度: O ( R × C ) O(R × C)

方法二:dp

上下左右走,取每一步的最小值…


复杂度分析

  • 时间复杂度: O ( ) O()
  • 空间复杂度: O ( ) O()
发布了691 篇原创文章 · 获赞 151 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105548223