时间:2020-7-27
题目地址:https://leetcode-cn.com/problems/01-matrix/
题目难度:Medium
题目描述:
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
示例 2:
输入:
0 0 0
0 1 0
1 1 1
输出:
0 0 0
0 1 0
1 2 1
注意:
给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
思路1:广度优先遍历
代码段1:通过
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
queue = collections.deque()
visited = [[0] * n for _ in range(m)]
res = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
queue.append((i,j))
visited[i][j] = 1
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
step = 0
while queue:
size = len(queue)
for i in range(size):
x, y = queue.popleft()
if matrix[x][y] == 1:
res[x][y] = step
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if new_x < 0 or new_x >= m or new_y < 0 or new_y >= n or visited[new_x][new_y] == 1:
continue
queue.append((new_x, new_y))
visited[new_x][new_y] = 1
step += 1
return res
总结:
- 自己已经写不出来了
-
BFS 使用队列,把每个还没有搜索到的点依次放入队列,然后再弹出队列的头部元素当做当前遍历点。BFS 总共有两个模板:
如果不需要确定当前遍历到了哪一层,BFS 模板如下。
while queue 不空:
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未访问过:
queue.push(该节点)
如果要确定当前遍历到了哪一层,BFS 模板如下。
这里增加了 level 表示当前遍历到二叉树中的哪一层了,也可以理解为在一个图中,现在已经走了多少步了。size 表示在当前遍历层有多少个元素,也就是队列中的元素数,我们把这些元素一次性遍历完,即把当前层的所有元素都向外走了一步。level = 0
while queue 不空:
size = queue.size()
while (size --) {
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未被访问过:
queue.push(该节点)
}
level ++;
上面两个是通用模板,在任何题目中都可以用,是要记住的!