Cut Off Trees for Golf Event
Hard
Topics
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
-1 if any leg is unreachable.Input: forest = [[1,2,3],[0,0,4],[7,6,5]] Output: 6
Example 2
Input: forest = [[1,2,3],[0,0,0],[7,6,5]] Output: -1
Example 3
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
- Collect every cell holding a tree, meaning a value above 1, and sort by height.
- Start at the top-left cell with a total of 0.
- For each tree in height order, BFS from the current position to it.
- 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 -1Complexity
- Time — O((m·n)²): up to
m·ntrees, each needing a BFS that visits up tom·ncells. 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 0is 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 totalimport java.util.*;
class Solution {
public int cutOffTree(int[][] grid) {
int R = grid.length, C = grid[0].length;
List<int[]> trees = new ArrayList<>();
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] > 1) trees.add(new int[]{grid[r][c], r, c});
trees.sort((a, b) -> a[0] - b[0]);
int pr = 0, pc = 0, total = 0;
for (int[] t : trees) {
int d = bfs(grid, pr, pc, t[1], t[2]);
if (d < 0) return -1;
total += d;
pr = t[1];
pc = t[2];
}
return total;
}
private int bfs(int[][] g, int sr, int sc, int tr, int tc) {
if (sr == tr && sc == tc) return 0;
int R = g.length, C = g[0].length;
boolean[][] vis = new boolean[R][C];
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{sr, sc});
vis[sr][sc] = true;
int[][] dirs = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
int d = 0;
while (!q.isEmpty()) {
int sz = q.size();
d++;
for (int i = 0; i < sz; i++) {
int[] cur = q.poll();
for (int[] dir : dirs) {
int nr = cur[0] + dir[0], nc = cur[1] + dir[1];
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || g[nr][nc] == 0) continue;
if (nr == tr && nc == tc) return d;
vis[nr][nc] = true;
q.add(new int[]{nr, nc});
}
}
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int cutOffTree(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
vector<array<int,3>> trees;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] > 1) trees.push_back({grid[r][c], r, c});
sort(trees.begin(), trees.end());
int dirs[4][2] = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
auto bfs = [&](int sr, int sc, int tr, int tc) -> int {
if (sr == tr && sc == tc) return 0;
vector<vector<char>> vis(R, vector<char>(C, 0));
queue<pair<int,int>> q;
q.push({sr, sc});
vis[sr][sc] = 1;
int d = 0;
while (!q.empty()) {
int sz = q.size();
d++;
for (int i = 0; i < sz; i++) {
auto cur = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int nr = cur.first + dirs[k][0], nc = cur.second + dirs[k][1];
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || grid[nr][nc] == 0) continue;
if (nr == tr && nc == tc) return d;
vis[nr][nc] = 1;
q.push({nr, nc});
}
}
}
return -1;
};
int pr = 0, pc = 0, total = 0;
for (auto& t : trees) {
int d = bfs(pr, pc, t[1], t[2]);
if (d < 0) return -1;
total += d;
pr = t[1];
pc = t[2];
}
return total;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var cutOffTree = function(grid) {
const R = grid.length, C = grid[0].length;
const trees = [];
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (grid[r][c] > 1) trees.push([grid[r][c], r, c]);
trees.sort((a, b) => a[0] - b[0]);
const bfs = (sr, sc, tr, tc) => {
if (sr === tr && sc === tc) return 0;
const vis = Array.from({ length: R }, () => new Array(C).fill(false));
let q = [[sr, sc]];
vis[sr][sc] = true;
let d = 0;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (q.length) {
const nq = [];
d++;
for (const [cr, cc] of q) {
for (const [dr, dc] of dirs) {
const nr = cr + dr, nc = cc + dc;
if (nr < 0 || nr >= R || nc < 0 || nc >= C || vis[nr][nc] || grid[nr][nc] === 0) continue;
if (nr === tr && nc === tc) return d;
vis[nr][nc] = true;
nq.push([nr, nc]);
}
}
q = nq;
}
return -1;
};
let pr = 0, pc = 0, total = 0;
for (const t of trees) {
const d = bfs(pr, pc, t[1], t[2]);
if (d < 0) return -1;
total += d;
pr = t[1];
pc = t[2];
}
return total;
};