A forest is an m × n grid of integers. A 0 is a cell you cannot walk on. A 1 is open ground. Any number above 1 is a tree of that height, and you can walk through tree cells too. No two trees have the same height.
You start at the top-left cell (0, 0) and move one cell up, down, left or right per step. You must cut every tree, strictly from the shortest to the tallest; you cut a tree by standing on it, and you may pass over taller trees without cutting them. Return the fewest steps needed, or −1 if some tree cannot be reached.
Example 1
Input: forest = [[1, 3, 0], [2, 4, 5]] Output: 5 Why: legs of 1, 2, 1 and 1 steps for trees 2, 3, 4, 5
2 more examples and the constraints
Example 2
Input: forest = [[1, 2, 0], [0, 0, 3]] Output: -1 Why: walls cut tree 3 off from the rest
Example 3
Input: forest = [[2, 1], [1, 3]] Output: 2 Why: tree 2 is under your feet, then 2 steps to tree 3
Constraints
- The grid has between 1 and 50 rows, and between 1 and 50 columns
- Each cell holds a value from 0 up to 1,000,000,000
- Tree heights are all different, and there is at least one tree
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort, then BFS each legO(T·m·n)
- Sort, then detour-first searchO(T·m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 forest | Verdict |
|---|---|---|---|
| Sort, then BFS each leg | O(T·m·n) | Passes; the standard answer | |
| Sort, then detour-first search | O(T·m·n) | Best; heads straight for the goal |
T = number of trees, m × n = grid size. Work is typical, not worst case.
Edge cases to test
- Tree at the start. [[2, 1], [1, 3]]: the first leg costs 0 steps.
- Unreachable tree. Walls around any tree make the answer −1, even if others were cut.
- Walking past taller trees. [[3, 2, 1]] costs 2: step to 2, then back onto 3.
- One cell. [[5]] is a single tree under your feet, so 0 steps.
Common mistakes
- Treating taller trees as walls; every non-zero cell is walkable.
- Forgetting that the start cell may itself hold the shortest tree, a leg of 0 steps.
- Marking cells visited across legs; each leg needs a fresh search.
How to talk through it
- 1Clarify. Can I walk over trees without cutting them? Are heights distinct? What if a tree is unreachable?
- 2Split into legs. The order is forced, so the answer is a sum of shortest paths between consecutive trees.
- 3Pick the search. Unweighted grid, so BFS per leg; then mention Hadlock’s detour trick to aim at the goal.
- 4Code it. Sort (height, row, col), loop over legs, return −1 as soon as a leg fails.
- 5Test out loud. Run a tree at the start, a walled-off tree and a single cell.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?