最小体力消耗路径

你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。

一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。

请你返回从左上角走到右下角的最小 体力消耗值

示例 1:

ex1

1
2
3
4
输入:heights = [[1,2,2],[3,8,2],[5,3,5]]
输出:2
解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。
这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。

示例 2:

ex2

1
2
3
输入:heights = [[1,2,3],[3,8,4],[5,3,5]]
输出:1
解释:路径 [1,2,3,4,5] 的相邻格子差值绝对值最大为 1 ,比路径 [1,3,5,3,5] 更优。

示例 3:

ex3

1
2
3
输入:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
输出:0
解释:上图所示路径不需要消耗任何体力。

提示:

  • rows == heights.length
  • columns == heights[i].length
  • 1 <= rows, columns <= 100
  • 1 <= heights[i][j] <= 106

代码:

62% 48%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public int minimumEffortPath(int[][] heights) {
int[][] dif=new int[heights.length][heights[0].length];
int[][] mark=new int[heights.length][heights[0].length];
int[] point={0,1,0,-1,0};
LinkedList<int[]> list=new LinkedList<>();
list.add(new int[]{0,0});
for(int i=0;i<dif.length;i++)
for(int j=0;j<dif[0].length;j++)
dif[i][j]=Integer.MAX_VALUE;
dif[0][0]=0;//Integer.MAX_VALUE;

while(list.size()!=0)
{
int[] t=list.removeFirst();
int x=t[0];
int y=t[1];
int x2;
int y2;
mark[x][y]=1;
int min=Integer.MIN_VALUE;
for(int i=0;i<4;i++)
{
x2=x+point[i];
y2=y+point[i+1];
if(x2<0||x2>=heights.length||y2<0||y2>=heights[0].length) continue;
//if(mark[x2][y2]==1) continue;
int d=Math.abs(heights[x2][y2]-heights[x][y]);
if(d<min)min=d;
int temp= Math.max(d,dif[x][y]);
// if(dif[x2][y2]==0)
// dif[x2][y2]=temp;
// else{
if(temp<dif[x2][y2])
{
dif[x2][y2]=temp;
list.addLast(new int[]{x2,y2});
}
//dif[x2][y2]=Math.min(dif[x2][y2],temp);
// }

}
}
return dif[dif.length-1][dif[0].length-1];
}

}