LeetCode 题解工作台

最小体力消耗路径

你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0…

category

7

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

对于本题,我们可以把每个格子当做图的一个节点,把相邻两个格子的高度差绝对值当做边的权重,因此本题是求解从最左上角的节点到最右下角的节点的连通性问题。 我们先构建一个边集,然后按照边的权重从小到大进行排序,逐个添加边,直到最左上角的节点和最右下角的节点连通为止,此时的边的权重就是题目的最小体力消耗值。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

 

示例 1:

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

示例 2:

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

示例 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
lightbulb

解题思路

方法一:并查集

对于本题,我们可以把每个格子当做图的一个节点,把相邻两个格子的高度差绝对值当做边的权重,因此本题是求解从最左上角的节点到最右下角的节点的连通性问题。

我们先构建一个边集,然后按照边的权重从小到大进行排序,逐个添加边,直到最左上角的节点和最右下角的节点连通为止,此时的边的权重就是题目的最小体力消耗值。

时间复杂度 O(m×n×log(m×n))O(m \times n \times \log(m \times n)),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别是二维数组的行数和列数。

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 UnionFind:
    def __init__(self, n):
        self.p = list(range(n))
        self.size = [1] * n

    def find(self, x):
        if self.p[x] != x:
            self.p[x] = self.find(self.p[x])
        return self.p[x]

    def union(self, a, b):
        pa, pb = self.find(a), self.find(b)
        if pa == pb:
            return False
        if self.size[pa] > self.size[pb]:
            self.p[pb] = pa
            self.size[pa] += self.size[pb]
        else:
            self.p[pa] = pb
            self.size[pb] += self.size[pa]
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)


class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        m, n = len(heights), len(heights[0])
        uf = UnionFind(m * n)
        e = []
        dirs = (0, 1, 0)
        for i in range(m):
            for j in range(n):
                for a, b in pairwise(dirs):
                    x, y = i + a, j + b
                    if 0 <= x < m and 0 <= y < n:
                        e.append(
                            (abs(heights[i][j] - heights[x][y]), i * n + j, x * n + y)
                        )
        e.sort()
        for h, a, b in e:
            uf.union(a, b)
            if uf.connected(0, m * n - 1):
                return h
        return 0
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidates should be able to identify the binary search pattern and the use of BFS/DFS for pathfinding.

  • question_mark

    Look for clarity in the explanation of the binary search strategy and its connection to grid traversal.

  • question_mark

    Watch for edge cases such as no height differences or minimal grid sizes.

warning

常见陷阱

外企场景
  • error

    Failing to recognize that the problem requires binary search over possible efforts rather than simply trying to traverse the grid directly.

  • error

    Not treating the grid as a graph and mistakenly thinking about each cell as an independent entity rather than part of a graph structure.

  • error

    Overlooking edge cases where no effort is required (e.g., all cells have the same height).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider applying the same approach to find the path with the minimum total effort rather than maximum effort.

  • arrow_right_alt

    Modify the problem to allow diagonal moves between cells and evaluate how it affects the approach.

  • arrow_right_alt

    Change the constraints, such as increasing the grid size or allowing negative heights, and analyze the impact on the algorithm.

help

常见问题

外企场景

最小体力消耗路径题解:二分·搜索·答案·空间 | LeetCode #1631 中等