15% off all plans & roadmaps Use code
See plansLeetCode 1631 · Solution & editorial
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.
Path With Minimum Effort is a Graph Traversal Patterns (DFS & BFS) problem, in the Shortest Path (Dijkstra's Algorithm) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Master Dijkstra's algorithm for finding shortest paths in weighted graphs with non-negative edges.
The reference solution runs in O(m * n * log(m * n)) time and O(m * n) space.
Path With Minimum Effort has been reported in interviews at Google, Houzz, ByteDance.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Path With Minimum Effort is a Graph Traversal Patterns (DFS & BFS) problem, in the Shortest Path (Dijkstra's Algorithm) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.