Minimum Steps to Cut Trees in Height Order
You are given a 2D grid forest of size m x n representing a forest.
Each cell can have one of the following values:
- 0 → blocked cell, cannot be visited
- 1 → empty cell, can be visited
- > 1 → a tree with that height, and this cell can also be visited
You start from cell (0, 0). In one move, you may walk exactly one cell in any of the four directions: up, down, left, or right. You are only allowed to move to cells that are not blocked.
Your task is to cut all trees in the forest in increasing order of height. When a tree is cut, that cell becomes an empty cell with value 1.
Return the minimum number of steps required to cut all the trees in the required order.
If it is impossible to cut all trees, return -1.
It is guaranteed that: all tree heights are distinct and there is at least one tree in the forest
Notes:
- If the starting cell (0, 0) itself contains a tree, you may cut it immediately with 0 steps.
- Cutting a tree does not block movement. After cutting, that cell becomes a normal walkable cell.
- You must always cut the next shortest remaining tree first.
Example 1:
Input: forest = [[1,2,3],[1,1,4],[7,6,5]]
Output: 6
Explanation:
The trees must be cut in this order: 2 -> 3 -> 4 -> 5 -> 6 -> 7.
One valid route is:
- Start at (0,0)
- Move to (0,1) and cut 2
- Move to (0,2) and cut 3
- Move to (1,2) and cut 4
- Move to (2,2) and cut 5
- Move to (2,1) and cut 6
- Move to (2,0) and cut 7
Total steps = 6.
Example 2:
Input: forest = [[1,2,3],[0,0,0],[7,6,5]]
Output: -1
Explanation:
You can cut 2, 3, but the trees in the last row cannot be reached because the blocked cells in the middle prevent access.
So, it is impossible to cut all trees.
Now Your Turn!
Pick the correct output for the given inputInput: forest = [[2,1,3],[0,0,4],[7,6,5]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- m == forest.length
- n == forest[i].length
- 1 <= m, n <= 50
- forest[i][j] is either 0, 1, or a tree height greater than 1
- 0 <= forest[i][j] <= 109
- All tree heights are distinct
- There is at least one tree in the forest