Leetcode 542. 01 矩阵

源代码 2024-10-4 14:10:21 109 0 来自 中国
标题

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.
Example1:

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

2.png Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
解题思绪

这道题的要求是求出每个cell到0的隔断,可以用BFS和DP两种方法来做。
方法时间复杂度空间复杂度BFSO(mn)O(mn)DPO(4mn)O(1)1. BFS

BFS的思绪是,找到出发点节点,然后以出发点为圆心,一层一层扩散的方式,遍历全部的节点。
BFS的实现模板,就是使用队列来实现。
模板代码如下:
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:55, Processed in 0.205141 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表