Cut Off Trees for Golf Event

Hard

Topics
ArrayBFSMatrix

You are given a grid where 0 is an impassable obstacle, 1 is walkable ground, and any value greater than 1 is a tree of that height (all tree heights are distinct). Starting at the top-left cell, you must cut all trees in order of increasing height, walking 4-directionally (you may walk through trees). Return the total number of steps, or -1 if some tree cannot be reached.

Example 1

011210032654012
Trees must be cut in increasing height order, so the route is fixed before any searching: the labels show the forced visiting order. The work is summing the shortest walk between consecutive trees, and the answer is -1 if any leg is unreachable.
2D grid — one row per line.
Input:  forest = [[1,2,3],[0,0,4],[7,6,5]]
Output: 6

Example 2

011210002543012
Input:  forest = [[1,2,3],[0,0,0],[7,6,5]]
Output: -1

Example 3

012310042765012
Input:  forest = [[2,3,4],[0,0,5],[8,7,6]]
Output: 6

Constraints

  • 1 <= m, n <= 50
  • 0 <= forest[i][j] <= 10^9
  • The top-left cell is walkable.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The order is forced: trees must be cut by increasing height, and all heights are distinct, so there is exactly one valid sequence. That removes all the search from the problem — nothing is being optimised globally.

What remains is a sequence of independent shortest-path queries: from the current position to the next tree. All moves cost one step and trees are walkable, so each leg is a plain BFS over the grid. Sum the legs; if any leg is unreachable the whole task is impossible.

Approach

  1. Collect every cell holding a tree, meaning a value above 1, and sort by height.
  2. Start at the top-left cell with a total of 0.
  3. For each tree in height order, BFS from the current position to it.
  4. Return -1 if a BFS fails; otherwise add its length and move the current position to that tree.

Dry Run

grid     1  2  3
         0  0  4
         7  6  5

trees sorted by height
  2 at (0,1), 3 at (0,2), 4 at (1,2), 5 at (2,2), 6 at (2,1), 7 at (2,0)

legs, each a BFS from the previous position
  (0,0) -> (0,1)   1
  (0,1) -> (0,2)   1
  (0,2) -> (1,2)   1
  (1,2) -> (2,2)   1
  (2,2) -> (2,1)   1
  (2,1) -> (2,0)   1

answer 6

  with row 1 fully blocked ([[1,2,3],[0,0,0],[7,6,5]]) the bottom row is
  unreachable and the answer is -1

Complexity

  • Time — O((m·n)²): up to m·n trees, each needing a BFS that visits up to m·n cells. At the stated 50×50 bound that is 2,500 searches over 2,500 cells; measured at 0.07s for a grid where every cell is a distinct tree.
  • Space — O(m·n) for one visited grid and one queue, reallocated per leg. The sort adds O(T log T), which is dominated.

Common Pitfalls

  • Trying to optimise the visiting order. The heights fix it; this is not a travelling-salesman problem, and treating it as one is the main way candidates lose the plot.
  • Treating trees as obstacles. Only 0 blocks movement; a tree can be walked over before it is cut.
  • Reusing one visited grid across legs. Each BFS starts fresh, because a cell visited on an earlier leg is perfectly usable on a later one.
  • Using depth-first search for a leg. Every move costs one, so BFS is required for the shortest path.
  • Forgetting that the start cell may itself hold the shortest tree, in which case the first leg costs 0 steps — the early if start == target: return 0 is what covers it.
  • Counting the number of cells on a path instead of the number of moves. Steps are edges here, so an adjacent target is 1, not 2.

Full Solution — all languages

class Solution:
    def cutOffTree(self, grid):
        from collections import deque
        R = len(grid); C = len(grid[0])
        trees = []
        for r in range(R):
            for c in range(C):
                if grid[r][c] > 1: trees.append((grid[r][c], r, c))
        trees.sort()
        def bfs(sr, sc, tr, tc):
            if sr == tr and sc == tc: return 0
            vis = [[False] * C for _ in range(R)]
            q = deque([(sr, sc)]); vis[sr][sc] = True; d = 0
            while q:
                d += 1
                for _ in range(len(q)):
                    cr, cc = q.popleft()
                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nr, nc = cr + dr, cc + dc
                        if nr < 0 or nr >= R or nc < 0 or nc >= C or vis[nr][nc] or grid[nr][nc] == 0: continue
                        if nr == tr and nc == tc: return d
                        vis[nr][nc] = True; q.append((nr, nc))
            return -1
        pr, pc, total = 0, 0, 0
        for _, tr, tc in trees:
            d = bfs(pr, pc, tr, tc)
            if d < 0: return -1
            total += d; pr, pc = tr, tc
        return total
Asked at Flipkart
SensAI
Beta
Tap the mic to stop voice mode