给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
mat 中至少有一个 0
题目链接:leetcode 542
思路:
可以采用广度遍历的方式来做,先把所有为 0 的元素进队列,然后依次计算出其临近的元素的距离,依次直到把矩阵中所有的元素的距离都计算完。文章来源:https://www.toymoban.com/news/detail-595594.html
class Solution:
def __init__(self):
self.INT_MAX = 100000
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
rows, cols = len(mat), len(mat[0])
res = [[self.INT_MAX for j in range(cols)] for i in range(rows)]
visited = [[0 for j in range(cols)] for i in range(rows)]
ss = []
for i in range(rows):
for j in range(cols):
if mat[i][j] == 0:
res[i][j] = 0
visited[i][j] = 1
ss.append((i, j))
while len(ss) > 0:
r, c = ss.pop(0)
if r>0 and visited[r-1][c] == 0:
ss.append((r-1, c))
visited[r-1][c] = 1
res[r-1][c] = min(res[r-1][c], res[r][c]+1)
if r+1<rows and visited[r+1][c] == 0:
ss.append((r+1, c))
visited[r+1][c] = 1
res[r+1][c] = min(res[r+1][c], res[r][c]+1)
if c>0 and visited[r][c-1] == 0:
ss.append((r, c-1))
visited[r][c-1] = 1
res[r][c-1] = min(res[r][c-1], res[r][c]+1)
if c+1<cols and visited[r][c+1] == 0:
ss.append((r, c+1))
visited[r][c+1] = 1
res[r][c+1] = min(res[r][c+1], res[r][c]+1)
return res
方法二,采用动态规划来做
文章来源地址https://www.toymoban.com/news/detail-595594.html
class Solution:
def __init__(self):
self.INT_MAX = 100000
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
rows, cols = len(mat), len(mat[0])
res = [[self.INT_MAX for j in range(cols)] for i in range(rows)]
visited = [[0 for j in range(cols)] for i in range(rows)]
ss = []
for i in range(rows):
for j in range(cols):
if mat[i][j] == 0:
res[i][j] = 0
### from 左上
for i in range(rows):
for j in range(cols):
if i-1>=0:
res[i][j] = min(res[i-1][j]+1, res[i][j])
if j-1>=0:
res[i][j] = min(res[i][j-1]+1, res[i][j])
### from 右上
for i in range(rows):
for j in range(cols-1, -1, -1):
if i-1>=0:
res[i][j] = min(res[i-1][j]+1, res[i][j])
if j+1<cols:
res[i][j] = min(res[i][j+1]+1, res[i][j])
## from 左下
for i in range(rows-1, -1, -1):
for j in range(cols):
if i+1<rows:
res[i][j] = min(res[i+1][j]+1, res[i][j])
if j-1>=0:
res[i][j] = min(res[i][j-1]+1, res[i][j])
## from 右下
for i in range(rows-1, -1, -1):
for j in range(cols-1, -1, -1):
if i+1<rows:
res[i][j] = min(res[i+1][j]+1, res[i][j])
if j+1<cols:
res[i][j] = min(res[i][j+1]+1, res[i][j])
return res
到了这里,关于leetcode 542. 01 矩阵的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!