Cut Off Trees for Golf Event solution explained
Cut Off Trees for Golf Event reduces to a chain of ordinary shortest-path questions: list every tree, sort the trees by height, and run a grid BFS from your current cell to the next tree, adding each distance to a running total. If any single BFS cannot reach its tree, the whole answer is -1. With T trees on an R by C grid that is O(T · R · C) time.
By Evin JohnPublished 8 min read
The problem in plain words
A field is drawn as a grid of integers. A 0 is an obstacle you cannot enter. A 1 is open ground. Any value above 1 is a tree, and the value is its height; no two trees share a height. You begin at the top-left cell and can step up, down, left or right. You must cut the trees shortest first, then the next shortest, and so on. Cutting a tree turns its cell into open ground, and you may walk over cells that still hold trees. Return the total number of steps needed to cut every tree, or -1 if that is impossible.
| Grid (rows) | Answer | Legs |
|---|---|---|
| [1,5,0] / [1,1,3] / [0,2,1] | 7 | Start to tree 2 is 3 steps, tree 2 to tree 3 is 2, tree 3 to tree 5 is 2 |
| [1,4,1] / [0,0,1] / [2,1,3] | 11 | The walk to tree 2 must pass tree 4 and tree 3 without cutting them: 6, then 2, then 3 |
| [1,3,1] / [0,0,0] / [1,2,1] | -1 | A full row of obstacles cuts tree 2 off from the start |
| [9] | 0 | You start on the only tree and cut it where you stand |
Questions worth asking first: can the starting cell be an obstacle, and what should happen if there are no trees at all? A reasonable default is 0 steps when nothing needs cutting. The solutions below assume the start can be stood on, so confirm that assumption with the interviewer.
Spotting the real structure
The story sounds like a routing problem, and that can push people toward something like the traveling salesman problem. It is not one. The heights are distinct and must be cut in increasing order, so the visiting order is fully decided before you take a step. What remains is a list of independent legs: start to the shortest tree, that tree to the next, and so on. The total is the sum of the shortest distance for each leg.
There is one more simplification. Cutting a tree only turns a walkable cell into another walkable cell, so the walls never change between legs. Every leg runs on the same static grid. That is why one reusable BFS helper is enough.
Slow approach: all-pairs distances
One brute force is to compute the distance between every pair of open cells with Floyd-Warshall, then read off each leg from the table. With N = R · C cells that costs O(N³) time and O(N²) memory, which is hopeless for a 50 by 50 grid but handy as a test oracle on tiny ones. A worse brute force explores every path between two cells with DFS; it is exponential and adds nothing. Either way, mention the slow version briefly and move on to per-leg BFS.
Main approach: sort, then BFS per leg
- Collect the treesScan the grid and store (height, row, column) for every cell above 1.
- Sort by heightSorting the tuples puts them in cutting order. With T trees this is O(T log T).
- Run one BFS per legFrom the current cell, BFS over cells that are not 0 until you reach the next tree. Return the depth, or -1 if the queue empties.
- Accumulate or bail outAdd each distance to the total and move the current cell to that tree. If any leg returns -1, return -1 immediately.
from collections import deque
def cut_all_trees(forest):
rows, cols = len(forest), len(forest[0])
trees = sorted((forest[r][c], r, c) for r in range(rows) for c in range(cols) if forest[r][c] > 1)
def steps(sr, sc, tr, tc):
if (sr, sc) == (tr, tc):
return 0
seen = {(sr, sc)}
queue = deque([(sr, sc, 0)])
while queue:
r, c, d = queue.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and forest[nr][nc] != 0 and (nr, nc) not in seen:
if (nr, nc) == (tr, tc):
return d + 1
seen.add((nr, nc))
queue.append((nr, nc, d + 1))
return -1
total, r, c = 0, 0, 0
for _, tr, tc in trees:
d = steps(r, c, tr, tc)
if d < 0:
return -1
total += d
r, c = tr, tc
return totalfunction cutAllTrees(forest) {
const rows = forest.length, cols = forest[0].length;
const trees = [];
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++)
if (forest[r][c] > 1) trees.push([forest[r][c], r, c]);
trees.sort((a, b) => a[0] - b[0]);
const steps = (sr, sc, tr, tc) => {
if (sr === tr && sc === tc) return 0;
const seen = new Uint8Array(rows * cols);
seen[sr * cols + sc] = 1;
let frontier = [[sr, sc]];
for (let d = 1; frontier.length; d++) {
const next = [];
for (const [r, c] of frontier) {
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
if (forest[nr][nc] === 0 || seen[nr * cols + nc]) continue;
if (nr === tr && nc === tc) return d;
seen[nr * cols + nc] = 1;
next.push([nr, nc]);
}
}
frontier = next;
}
return -1;
};
let total = 0, r = 0, c = 0;
for (const [, tr, tc] of trees) {
const d = steps(r, c, tr, tc);
if (d < 0) return -1;
total += d;
r = tr;
c = tc;
}
return total;
}Note the early exit inside the BFS: the distance is returned as soon as the target cell is generated, not when it is later popped. That saves a full layer of work on every leg and is safe because every edge has the same cost. The JavaScript sort needs a numeric comparator, since the default sort compares values as strings and would put height 10 before height 9.
Complexity
| Part | Time | Extra space |
|---|---|---|
| Collect and sort trees | O(R · C + T log T) | O(T) |
| One BFS leg | O(R · C) | O(R · C) for the visited set and queue |
| All legs | O(T · R · C), which is O((R · C)²) when most cells are trees | O(R · C), reused per leg |
| Floyd-Warshall oracle | O((R · C)³) | O((R · C)²) |
If the interviewer asks for something faster per leg, A* with Manhattan distance as the heuristic is the standard answer, since that heuristic never overestimates on a four-direction grid. Another option some candidates mention is Hadlock's algorithm, which counts detours away from the target. Both keep the same worst case but usually explore far fewer cells.
Edge cases to test
- The start cell is itself a tree, possibly the shortest one: that leg costs 0.
- A single-cell grid, with or without a tree.
- No trees at all: the loop never runs and the total stays 0.
- A tree sealed off by obstacles, which must produce -1 even if every other tree is reachable.
- Heights given in a scrambled layout, to prove the code sorts rather than scanning in grid order.
- Large grids where most cells are trees, which is the worst case for the number of legs.
Common mistakes
- Blocking tree cells during BFS. Only 0 is an obstacle, and the second sample grid above fails if trees block the path.
- Cutting trees in grid order, or greedily walking to the nearest tree, instead of following the heights.
- Forgetting that the walk starts at the top-left cell and not at the first tree.
- Reusing one visited set across legs. Each leg needs a fresh one.
- Sorting JavaScript numbers without a comparator.
- Treating -1 from one leg as a distance and adding it to the total.
Saying it out loud
Fictional example
- Candidate
- The heights are unique and the order is fixed, so this is not a route-choice problem. I just need the shortest distance for each consecutive pair: start to the smallest tree, then tree to tree.
- Candidate
- Walls are only the zeros, and cutting never changes that, so each leg is a BFS on the same grid. I will sum the legs and return -1 if any BFS fails.
- Candidate
- That is T searches, each linear in the grid, so O(T times R times C). If that is too slow I can swap the BFS for A* with a Manhattan heuristic.
Related problems in this set
When the board itself becomes the node, the search looks like Sliding Puzzle. When picking things up changes where you may walk, the state has to carry what you hold, which is exactly what Shortest Path to Get All Keys does with a bitmask. For broader practice on BFS, sorting and grid traversal, see the algorithm interview questions.
Using Natively while you practice
If you practice this problem from a screenshot, Natively can read the grid description and suggest the sort-then-BFS plan, so you can compare it against your own reasoning after a timed attempt. It also keeps a transcript of a mock session on your machine, which makes it easy to see whether you called out the trees-are-walkable rule early. The AI interview assistant page explains how it works on Mac and Windows.
Questions people ask
How do you solve Cut Off Trees for Golf Event?
Collect every tree, sort them by height, then run a BFS on the grid from your current cell to the next tree and add the distance to a total. If any BFS cannot reach its tree, return -1.
Can you walk through trees you have not cut yet?
Yes. Only cells with value 0 block movement. Treating uncut trees as walls is a common bug that turns solvable grids into -1.
What is the time complexity?
With T trees on an R by C grid, each BFS is O(R · C), so the total is O(T · R · C). Sorting the trees adds O(T log T).
Is this a traveling salesman problem?
No. The heights are distinct and must be cut in increasing order, so the visiting order is fixed. Only the distance of each leg has to be computed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
