import heapq
def min_steps_to_destination(m, n, T, grid):
# 定义四个方向移动
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# 优先队列,格式:(步数, x, y, 剩余爆发次数)
pq = [(0, 0, 0, 3)] # 初始位置 (0,0),步数为 0,爆发次数 3
visited = set() # 记录访问过的状态
while pq:
steps, x, y, burst = heapq.heappop(pq)
# 如果到达终点,返回步数
if x == m - 1 and y == n - 1:
return steps
# 记录当前状态
if (x, y, burst) in visited:
continue
visited.add((x, y, burst))
# 遍历四个方向
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n: # 确保新位置在范围内
height_diff = abs(grid[nx][ny] - grid[x][y])
if height_diff <= 1:
heapq.heappush(pq, (steps + 1, nx, ny, burst))
elif height_diff <= t and burst> 0:
heapq.heappush(pq, (steps + 1, nx, ny, burst - 1))
return -1 # 无法到达终点
# 读取输入
m, n, T = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(m)]
# 计算最短步数
print(min_steps_to_destination(m, n, T, grid))
主要思路
- 建图:
读取 m × n 的矩阵。
每个格子的数值表示 高度。
只能上下左右移动。
- BFS + 优先队列
普通移动时,高度差不能超过1。
如果高度差 超过1但小于等于T,可使用 爆发技能(最多3次)。
使用 队列(heapq) 进行搜索,记录 (当前步数, x, y, 剩余爆发次数)。
- 终点条件
到达右下角 (m-1, n-1) 结束。
本文暂时没有评论,来添加一个吧(●'◡'●)