RY 's Blog

## LeetCode:542. 01 Matrix-DP

2019-05-23

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

## 题目: 01-matrix

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.

## 分析：

$$matrix[i][j] = min(left, top, right, bottom) + 1$$

1. 遍历matrix矩阵，matrix[i][j]不为0，计算 leftCell 跟 topCell最小值，再加1.
2. 再倒叙遍历matrix, matrix[i][j]不为0, 先计算rightCell 跟 topCell的最小值，再跟min(left, top)的值比较