Featured image of post 542. 01 矩阵

542. 01 矩阵

题目描述

给定一个由 01 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。

两个相邻元素间的距离为 1

示例 1:

  • 输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
  • 输出:[[0,0,0],[0,1,0],[0,0,0]]

示例 2:

  • 输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
  • 输出:[[0,0,0],[0,1,0],[1,2,1]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • mat 中至少有一个 0

解法一:BFS

 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
func updateMatrix(mat [][]int) [][]int {
    h, w := len(mat), len(mat[0])
    var queue [][2]int
    dirs := [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
    res, visited := make([][]int, h), make([][]bool, h)
    for i := 0; i < h; i++ {
        res[i] = make([]int, w)
        visited[i] = make([]bool, w)
        for j := 0; j < w; j++ {
            if mat[i][j] == 0 {
                queue = append(queue, [2]int{i, j})
                visited[i][j] = true
            }
        }
    }
    length := 0
    for len(queue) > 0 {
        cnt := len(queue)
        length++
        for cnt > 0 {
            cur := queue[0]
            queue = queue[1:]
            for _, dir := range dirs {
                ni, nj := cur[0]+dir[0], cur[1]+dir[1]
                if 0 <= ni && ni < h && 0 <= nj && nj < w && !visited[ni][nj] {
                    visited[ni][nj] = true
                    res[ni][nj] = length
                    queue = append(queue, [2]int{ni, nj})
                }
            }
            cnt--
        }
    }
    return res
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/07/30 17:39:35
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计