542. 01 Matrix
- Total Accepted: 2993
- Total Submissions: 8962
- Difficulty: Medium
- Contributors:
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.Example 1:
Input:
0 0 0 0 1 0 0 0 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
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,遍历矩阵的每个点,若不为0,从到这个点距离为1的点开始寻找0,若无则到距离为2的点,直到找到,记录距离。但这样做需要一个四重循环,在测试数据较大的时候会超时,代码如下:
于是转换思路,可以通过前面遍历过的点的已知数据来减少时间,若前一个点到0的距离为2,则这个点到0的距离至多为3。再进一步,每一给点都判断与它相邻的四个点,确定到0的最短距离,这样只需要遍历两次,一次从头到尾,一次从尾到头即可。代码如下: