classSolution:
def minimumTime(self, grid: List[List[int]]) -> int:
if grid[0][1] > 1 and grid[1][0] > 1:
return -1
max_row = len(grid) - 1
max_col = len(grid[0]) - 1
# 此处需要计算最小路径, 可以使用a* 或者dijkstra或者广度优先
# 先用dijkstra来进行计算
stable_set = set()
value_queue = []
heapq.heappush(value_queue, (0, (0, 0)))
def handler_next_pos(m ,n, value):
if (m, n) not in stable_set:
v = grid[m][n]
v = max(value + 1, v)
if (v - value) % 2 == 0:
v += 1
heapq.heappush(value_queue, (v, (m, n)))
while heapq:
value, pos = heapq.heappop(value_queue)
if pos in stable_set:
continue
if pos == (max_row, max_col):
return value
i, j = pos
if i > 0:
m, n = i-1, j
handler_next_pos(m, n, value)
if j > 0:
m, n = i, j - 1
handler_next_pos(m, n, value)
if i < max_row:
m, n = i+1, j
handler_next_pos(m, n, value)
if j < max_col:
m, n = i, j + 1
handler_next_pos(m, n, value)
stable_set.add(pos)
raise Exception
稍微改改就是 A* 了
classSolution:
def minimumTime(self, grid: List[List[int]]) -> int:
if grid[0][1] > 1 and grid[1][0] > 1:
return -1
max_row = len(grid) - 1
max_col = len(grid[0]) - 1
# 此处需要计算最小路径, 可以使用a* 或者dijkstra或者广度优先
# 先用a *来进行计算
stable_set = set()
value_queue = []
# 期望距离, 真实距离, 坐标
heapq.heappush(value_queue, (max_row + max_col, 0, (0, 0)))
def handler_next_pos(m ,n, value):
if (m, n) not in stable_set:
v = grid[m][n]
v = max(value + 1, v)
if (v - value) % 2 == 0:
v += 1
e_v = v + max_col + max_row - m - n
heapq.heappush(value_queue, (e_v, v, (m, n)))
while heapq:
_, value, pos = heapq.heappop(value_queue)
if pos in stable_set:
continue
if pos == (max_row, max_col):
return value
i, j = pos
if i > 0:
m, n = i-1, j
handler_next_pos(m, n, value)
if j > 0:
m, n = i, j - 1
handler_next_pos(m, n, value)
if i < max_row:
m, n = i+1, j
handler_next_pos(m, n, value)
if j < max_col:
m, n = i, j + 1
handler_next_pos(m, n, value)
stable_set.add(pos)
raise Exception
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步