1631. Path With Minimum Effort (M)

https://leetcode.com/problems/path-with-minimum-effort/

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

Example 1:

Example 2:

Example 3:

Constraints:

  • rows == heights.length

  • columns == heights[i].length

  • 1 <= rows, columns <= 100

  • 1 <= heights[i][j] <= 106

Solution:

我们常见的二维矩阵题目,如果让你从左上角走到右下角,比较简单的题一般都会限制你只能向右或向下走,但这道题可没有限制哦,你可以上下左右随便走,只要路径的「体力消耗」最小就行。

如果你把二维数组中每个 (x, y) 坐标看做一个节点,它的上下左右坐标就是相邻节点,它对应的值和相邻坐标对应的值之差的绝对值就是题目说的「体力消耗」,你就可以理解为边的权重。

这样一想,是不是就在让你以左上角坐标为起点,以右下角坐标为终点,计算起点到终点的最短路径?Dijkstra 算法是不是可以做到?

只不过,这道题中评判一条路径是长还是短的标准不再是路径经过的权重总和,而是路径经过的权重最大值

明白这一点,再想一下使用 Dijkstra 算法的前提,加权有向图,没有负权重边,求最短路径,OK,可以使用,咱们来套框架。

二维矩阵抽象成图,我们先实现一下图的 adj 方法,之后的主要逻辑会清晰一些:

类似的,我们现在认为一个二维坐标 (x, y) 是图中的一个节点,所以这个 State 类也需要修改一下:

接下来,就可以套用 Dijkstra 算法的代码模板了:

你看,稍微改一改代码模板,这道题就解决了。

Last updated

Was this helpful?