题目:
你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,
其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,
且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。
你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。
一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。
请你返回从左上角走到右下角的最小 体力消耗值 。
![在这里插入图片描述](https://img-blog.csdnimg.cn/4be52b33229a4a66b795e604fff94412.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Li_5ZSQ5a6L,size_17,color_FFFFFF,t_70,g_se,x_16)
输入:heights = [[1,2,2],[3,8,2],[5,3,5]]
输出:2
解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。
这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。
![在这里插入图片描述](https://img-blog.csdnimg.cn/5018227488b841a2a37cd2114388601a.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Li_5ZSQ5a6L,size_18,color_FFFFFF,t_70,g_se,x_16)
输入:heights = [[1,2,3],[3,8,4],[5,3,5]]
输出:1
解释:路径 [1,2,3,4,5] 的相邻格子差值绝对值最大为 1 ,比路径 [1,3,5,3,5] 更优。
![在这里插入图片描述](https://img-blog.csdnimg.cn/c80e8d7a9b444d289230323fccf2b1f7.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Li_5ZSQ5a6L,size_18,color_FFFFFF,t_70,g_se,x_16)
输入: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
-------------------
思路:
图的问题也可以采用dfs和bfs进行求解,题目注释里给出高度值的范围为[1,1000000],
因此结果最大为100000,可以采用二分法进行夹逼求得结果。
注意:如果不采用二分法,而是采用传统回溯法,会导致超时
------------------
class Solution {
private int row;
private int col;
private int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int minimumEffortPath(int[][] heights) {
row = heights.length;
col = heights[0].length;
int left = 0;
int right = 1000000;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (!dfs(0, 0, mid, heights, new boolean[row][col])) {
left = mid + 1;
}else {
right = mid - 1;
}
}
return left;
}
private boolean dfs(int x, int y, int target, int[][]heights, boolean[][] visited) {
if (x == row - 1 && y == col - 1) {
return true;
}
visited[x][y] = true;
for (int[] d : dir) {
int nx = x + d[0];
int ny = y + d[1];
if (0 <= nx && nx < row && 0 <= ny && ny < col && !visited[nx][ny]) {
if (Math.abs(heights[nx][ny] - heights[x][y]) > target) {
continue;
}
if (dfs(nx, ny, target, heights, visited)) {
return true;
}
}
}
return false;
}
}
LC