Cut Off Trees for Golf Event - Problem
Golf Course Forest Clearing Challenge
You're tasked with clearing a forest to create a golf course! The forest is represented as an
•
•
•
Rules:
1. Start at position
2. Move in 4 directions: north, east, south, west
3. Must cut trees in order from shortest to tallest
4. After cutting a tree, the cell becomes empty (value = 1)
Goal: Return the minimum steps needed to cut all trees, or
Example: If you have trees of heights [3, 4, 2], you must cut them in order: height 2 → height 3 → height 4
You're tasked with clearing a forest to create a golf course! The forest is represented as an
m × n grid where each cell contains:•
0 - Obstacle (cannot walk through)•
1 - Empty space (can walk through)•
Number > 1 - Tree with height (can walk through and cut)Rules:
1. Start at position
(0, 0)2. Move in 4 directions: north, east, south, west
3. Must cut trees in order from shortest to tallest
4. After cutting a tree, the cell becomes empty (value = 1)
Goal: Return the minimum steps needed to cut all trees, or
-1 if impossible.Example: If you have trees of heights [3, 4, 2], you must cut them in order: height 2 → height 3 → height 4
Input & Output
example_1.py — Basic Forest
$
Input:
forest = [[1,2,3],[0,0,4],[7,6,5]]
›
Output:
6
💡 Note:
Trees to cut: [2,3,4,5,6,7]. Start at (0,0), go to (0,1) for tree 2 (1 step), then (0,2) for tree 3 (1 step), then (1,2) for tree 4 (1 step), then (2,2) for tree 5 (1 step), then (2,1) for tree 6 (1 step), then (2,0) for tree 7 (1 step). Total: 6 steps.
example_2.py — Blocked Path
$
Input:
forest = [[1,2,3],[0,0,0],[7,6,5]]
›
Output:
-1
💡 Note:
Trees exist at positions with values > 1, but middle row is all obstacles (0). Cannot reach trees in the bottom row from the top row, so return -1.
example_3.py — Single Tree
$
Input:
forest = [[2,1,1],[1,1,1],[1,1,1]]
›
Output:
0
💡 Note:
Only one tree with height 2 at position (0,0), which is also the starting position. No movement needed, so return 0 steps.
Constraints
- 1 ≤ forest.length ≤ 50
- 1 ≤ forest[i].length ≤ 50
- 0 ≤ forest[i][j] ≤ 109
- No two trees have the same height
- At least one tree exists
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Forest
Find all trees and note their heights - like making a treasure map
2
Plan the Route
Sort trees by height to determine the required visitation order
3
Navigate Optimally
Use BFS to find shortest path between consecutive tree locations
4
Sum Total Distance
Add up all the shortest distances to get minimum total steps
Key Takeaway
🎯 Key Insight: Break the problem into multiple shortest-path subproblems, using BFS to guarantee optimal distances between consecutive trees in height-sorted order.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code