试一下这个 DP[i][j][t]是t次迭代之后position i,j被感染需要的天数 最后return max(DP[i][j][m*n] where M[i][j] = 1, m = len(M), n = len(M[0]) 那 DP[i][j][t] = 1 + min_{x,y where M[x][y] != 0 and x,y is neighbor of i, j} DP[x][y][t - 1] 初始条件DP[i][j][t] = 0 if M[i][j] = 2 else DP[i][j][t] = infinity
【在 j*****d 的大作中提到】 : 你用dp写出来了么?
l*r
7 楼
这是code class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) DP = [[[float('inf') for k in range(m*n)] for j in range(n)] for i in range(m)] for i in range(m): for j in range(n): for t in range(m*n): if grid[i][j] == 2: DP[i][j][t] = 0 else: DP[i][j][t] = float('inf')
for t in range(1, m*n): for i in range(m): for j in range(n): if i + 1 < m and grid[i + 1][j] != 0: DP[i][j][t] = min(DP[i][j][t], 1 + DP[i + 1][j][t - 1]) if i - 1 >= 0 and grid[i - 1][j] != 0: DP[i][j][t] = min(DP[i][j][t], 1 + DP[i - 1][j][t - 1]) if j + 1 < n and grid[i][j + 1] != 0: DP[i][j][t] = min(DP[i][j][t], 1 + DP[i][j + 1][t - 1]) if j - 1 >= 0 and grid[i][j - 1] != 0: DP[i][j][t] = min(DP[i][j][t], 1 + DP[i][j - 1][t - 1])
res = -float('inf') noOnesFlag = True for i in range(m): for j in range(n): if grid[i][j] == 1 and DP[i][j][m*n - 1] > res: res = DP[i][j][m*n - 1] noOnesFlag = False if noOnesFlag == True: return 0 return res if res < float('inf') else -1
【在 l******r 的大作中提到】 : 这是code : class Solution: : def orangesRotting(self, grid: List[List[int]]) -> int: : m = len(grid) : n = len(grid[0]) : DP = [[[float('inf') for k in range(m*n)] for j in range(n)] for i : in range(m)] : for i in range(m): : for j in range(n): : for t in range(m*n):