Cut Off Trees for Golf Event — LeetCode 675 Python Solution
HardBreadth-First SearchArrayMatrixHeap (Priority Queue)
- Problem
- #675
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) auxiliary |
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
LeetCode 407Trapping Rain Water IIHardLeetCode 1263Minimum Moves to Move a Box to Their Target LocationHardLeetCode 1368Minimum Cost to Make at Least One Valid Path in a GridHardLeetCode 2146K Highest Ranked Items Within a Price RangeMediumLeetCode 2290Minimum Obstacle Removal to Reach CornerHardLeetCode 2577Minimum Time to Visit a Cell In a GridHard
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.