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,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
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.
------------------------------------------------------------------------
Nice problem!!! DFS first but TLE due to dup check. Then BFS pass the problem:
import sys
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
rows,cols = len(matrix),len(matrix[0])
res = [[0 if matrix[i][j] == 0 else sys.maxsize for j in range(cols)] for i in range(rows)]
vis = [(i,j) for j in range(cols) for i in range(rows) if matrix[i][j] == 0 ]
layers = [set(vis),set()]
c,n,dis = 0,1,0
while (layers[c]):
for (x,y) in layers[c]:
for (dx,dy) in [(0,1),(1,0),(0,-1),(-1,0)]:
nx,ny = x+dx,y+dy
if (nx>=0 and nx<rows and ny>=0 and ny<cols and dis+1<res[nx][ny]):
res[nx][ny] = dis+1
layers[n].add((nx,ny))
layers[c].clear()
n,c = c,n
dis += 1
return res
DP is also a nice solution! From left up to right down in the first round, then from right down to left up for the 2nd round!!!

本文探讨了在由0和1组成的矩阵中寻找每个单元格到最近0元素的距离的算法。通过深度优先搜索(DFS)和广度优先搜索(BFS)的方法,详细解释了如何有效地解决这个问题,并提供了一个Python实现的示例。此外,还提到了动态规划(DP)作为一种替代解决方案。
1万+

被折叠的 条评论
为什么被折叠?



