HardNo. 0675
Cut Off Trees for Golf Event — LeetCode 675 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Breadth-First Search, Array, Matrix, Heap (Priority Queue)
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix.
Example
- Input
- forest = [[1,2,3],[0,0,4],[7,6,5]]
- Output
- 6
- Explanation
- Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
Python solution
class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
def f(i, j, x, y):
return abs(i - x) + abs(j - y)
def bfs(i, j, x, y):
q = [(f(i, j, x, y), i, j)]
dist = {i * n + j: 0}
while q:
_, i, j = heappop(q)
step = dist[i * n + j]
if (i, j) == (x, y):
return step
for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
c, d = i + a, j + b
if 0 <= c < m and 0 <= d < n and forest[c][d] > 0:
if c * n + d not in dist or dist[c * n + d] > step + 1:
dist[c * n + d] = step + 1
heappush(q, (dist[c * n + d] + f(c, d, x, y), c, d))
return -1
m, n = len(forest), len(forest[0])
trees = [
(forest[i][j], i, j) for i in range(m) for j in range(n) if forest[i][j] > 1
]
trees.sort()
i = j = 0
ans = 0
for _, x, y in trees:
t = bfs(i, j, x, y)
if t == -1:
return -1
ans += t
i, j = x, y
return ansComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 675. Cut Off Trees for Golf Event is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0407 | Trapping Rain Water II | Hard |
| 1263 | Minimum Moves to Move a Box to Their Target Location | Hard |
| 1368 | Minimum Cost to Make at Least One Valid Path in a Grid | Hard |
| 2146 | K Highest Ranked Items Within a Price Range | Medium |
| 2290 | Minimum Obstacle Removal to Reach Corner | Hard |
| 2577 | Minimum Time to Visit a Cell In a Grid | Hard |
Frequently asked questions
- How hard is LeetCode 675. Cut Off Trees for Golf Event?
LeetCode 675. Cut Off Trees for Golf Event is rated Hard on LeetCode.
- What is the time complexity of LeetCode 675. Cut Off Trees for Golf Event?
The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 675. Cut Off Trees for Golf Event?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 675. Cut Off Trees for Golf Event cover?
LeetCode 675. Cut Off Trees for Golf Event is tagged Breadth-First Search, Array, Matrix and Heap (Priority Queue) on LeetCode.