给定一个由 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
思路:
可以采用广度遍历的方式来做,先把所有为 0 的元素进队列,然后依次计算出其临近的元素的距离,依次直到把矩阵中所有的元素的距离都计算完。
class Solution:def __init__(self):self.INT_MAX = 100000def 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] = 0visited[i][j] = 1ss.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] = 1res[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] = 1res[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] = 1res[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] = 1res[r][c+1] = min(res[r][c+1], res[r][c]+1)return res
方法二,采用动态规划来做
class Solution:def __init__(self):self.INT_MAX = 100000def 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