Python 0675.py
class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
width = len(forest[0])
height = len(forest)
# add all trees to min-heap
trees = []
for y in range(height):
for x in range(width):
if forest[y][x] > 1:
heappush(trees, (forest[y][x], x, y))
steps = 0
todo = [ ( 0, 0 ) ]
while trees:
# next tree
th, tx, ty = heappop(trees)
seen = set()
cut = False
while todo and not cut:
next = []
for x, y in todo:
if x == tx and y == ty:
cut = True
next = [ (x, y) ]
forest[y][x] = 1
break
if forest[y][x] == 0:
continue
if (x, y) in seen:
continue
seen.add((x, y))
if x > 0:
next.append((x - 1, y))
if x < width - 1:
next.append((x + 1, y))
if y > 0:
next.append((x, y - 1))
if y < height - 1:
next.append((x, y + 1))
if not cut:
steps += 1
todo = next
if not cut:
return -1
return steps
Difficulty
and has an acceptance rate of about 37% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Heap (Priority Queue)
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method cutOffTree that computes the minimum number of steps required to cut down all trees in a forest grid, visiting them in ascending order of height. The forest is represented as a 2-dimensional list where 0 denotes an impassable obstacle, 1 denotes walkable ground, and any value greater than 1 denotes a tree with a specific height. The algorithm proceeds by first collecting all trees, then repeatedly performing a breadth-first search (BFS) from the current position to the next tree in height order, updating the step count as it moves. If any tree cannot be reached, the method returns -1.
Collecting Trees in Height Order
The first phase scans the entire grid to locate every tree. For each cell whose value exceeds 1, a tuple containing the tree’s height and its coordinates is pushed onto a min-heap. The heap property guarantees that the smallest height tree will be extracted first, ensuring the required visitation order.
trees = []
for y in range(height):
for x in range(width):
if forest[y][x] > 1:
heappush(trees, (forest[y][x], x, y))
Breadth-First Search Loop
The main loop continues until the heap of trees is empty. In each iteration the next tree’s height and coordinates are retrieved from the heap.
while trees:
th, tx, ty = heappop(trees)
A BFS is then launched from the current location (initially the top-left corner (0, 0)). The search maintains a list todo representing the frontier of positions to explore at the current depth, a set seen to avoid revisiting cells, and a flag cut that becomes true when the target tree is reached.
seen = set()
cut = False
while todo and not cut:
next = []
for x, y in todo:
if x == tx and y == ty:
cut = True
next = [(x, y)]
forest[y][x] = 1
break
if forest[y][x] == 0:
continue
if (x, y) in seen:
continue
seen.add((x, y))
if x > 0:
next.append((x - 1, y))
if x < width - 1:
next.append((x + 1, y))
if y > 0:
next.append((x, y - 1))
if y < height - 1:
next.append((x, y + 1))
if not cut:
steps += 1
todo = next
When the target coordinates match the current cell, the tree is “cut” by setting its value to 1, and the loop exits. If the frontier becomes empty without reaching the tree, the method returns -1, indicating an unreachable tree.
Updating the Step Counter
The variable steps accumulates the total number of moves taken. After each layer of BFS expansion (i.e., after processing all positions at the current distance), the step counter is incremented, reflecting the passage of one unit of distance.
if not cut:
steps += 1
Handling Edge Conditions
The algorithm gracefully deals with several edge conditions:
- Obstacles: Cells with value
0are ignored during BFS, preventing traversal through impassable terrain. - Unreachable Trees: If a tree cannot be reached from the current position, the BFS frontier empties, triggering an early return of
-1. - Starting Position Blocked: Should the initial cell
(0, 0)be an obstacle, the first BFS will have no viable moves, leading to the same-1outcome. - Multiple Trees with Same Height: The heap orders trees by height first; when heights are equal, the order defaults to the insertion order, which does not affect correctness because any order among equal-height trees satisfies the problem constraints.
- In-Place Modification: After a tree is cut, its cell value is set to
1, converting it into walkable ground for subsequent searches without needing a separate visited map for the entire grid.
Performance Optimizations
The implementation incorporates several techniques that improve runtime efficiency:
- Min-Heap for Ordering: By using a heap to store trees, the algorithm avoids sorting the entire list of trees up front, extracting the next smallest height in logarithmic time.
- Frontier List Instead of Queue: The BFS uses two lists (
todoandnext) to represent the current and next layers. This approach eliminates the overhead of deque operations while still providing level-by-level expansion. - Early Termination on Target Reach: As soon as the target tree’s coordinates are encountered, the inner loop breaks, preventing unnecessary exploration of remaining frontier nodes at the same depth.
- Set for Visited Tracking: The
seenset ensures each cell is processed at most once per BFS, avoiding redundant work and reducing the number of neighbor checks. - In-Place Grid Update: Converting a cut tree to
1directly in the original grid removes the need for an auxiliary structure to track cleared cells, saving memory and simplifying neighbor checks.
Overall, the method systematically progresses through the forest, leveraging a heap for ordered tree selection and an efficient BFS implementation to compute the minimal step count required to clear all trees.
ELI5 - Simplified Explanation
Imagine there is a big grid filled with different trees. Some spots have trees with numbers on them, and some spots are empty or have rocks. The goal is to visit every single tree, starting from the shortest ones and working up to the tallest ones.
First, the code looks at the whole garden to find all the trees and keeps them in a list so the shortest ones can be picked first. It starts with a little person standing at the top corner of the garden.
Next, the code starts a loop that keeps going until every tree is visited. Inside the loop, it picks the next shortest tree to aim for. The code then starts a search to find the way to that tree. It looks at every square around the current spot and moves outward like a wave. Each time the search has to step into a new square to get closer to the target tree, it adds one to the count of total steps taken.
When the search reaches the tree, the tree is cut down, which means it turns into an empty grassy spot. The person stays at that spot and prepares to find the next shortest tree. If the search reaches a point where it is impossible to get to a tree because of rocks, the mission stops. Once every tree has been visited and cut down, the total number of steps taken to travel through the forest is known.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 990: Satisfiability of Equality Equations
- problem 1019: Next Greater Node In Linked List
- problem 839: Similar String Groups
- problem 864: Shortest Path to Get All Keys
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality