Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #675: Cut Off Trees for Golf Event

In this guide, we solve Leetcode #675 Cut Off Trees for Golf Event in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Breadth-First Search, Array, Matrix, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

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 ans

Complexity

The time complexity is O(n log n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy