542. 01 Matrix

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1:

Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]

Constraints:

  • m == mat.length

  • n == mat[i].length

  • 1 <= m, n <= 104

  • 1 <= m * n <= 104

  • mat[i][j] is either 0 or 1.

  • There is at least one 0 in mat.

My Solutions:

和64题类似

还有一种从0点周边出发,一层一层增加的解法。

  • For convinience, let's call the cell with value 0 as zero-cell, the cell has with value 1 as one-cell, the distance of the nearest 0 of a cell as distance.

  • Firstly, we can see that the distance of all zero-cells are 0.

  • Same idea with Topology Sort, we process zero-cells first, then we use queue data structure to keep the order of processing cells, so that cells which have the smaller distance will be processed first. - Then we expand the unprocessed neighbors of the current processing cell and push into our queue.

  • Afterall, we can achieve the minimum distance of all cells in our matrix.

Last updated