Cut Off Trees For Golf Event Problem
Description
LeetCode Problem 675.
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. In this matrix:
- 0 means the cell cannot be walked through.
- 1 represents an empty cell that can be walked through.
- A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.
In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.
You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).
Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.
You are guaranteed that no two trees have the same height, and there is at least one tree needs to be cut off.
Example 1:
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.
Example 2:
Input: forest = [[1,2,3],[0,0,0],[7,6,5]]
Output: -1
Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.
Example 3:
Input: forest = [[2,3,4],[0,0,5],[8,7,6]]
Output: 6
Explanation: You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
Constraints:
- m == forest.length
- n == forest[i].length
- 1 <= m, n <= 50
- 0 <= forest[i][j] <= 10^9
Solution
Approach: Sort the Trees, then BFS Between Consecutive Trees
The order of the cuts is fixed: shortest tree first. So the walk splits into independent legs: from (0, 0) to the shortest tree, from there to the second shortest, and so on. Each leg should be as short as possible, and a shorter leg never makes a later leg longer, because where we stand after a leg is always the same tree. The answer is the sum of the shortest leg lengths.
- Collect every cell with a value greater than 1 as
(height, row, col)and sort by height. - Start at
(0, 0). For each tree in order, run a breadth-first search from the current cell to the tree. BFS on a grid with equal step costs finds the fewest steps. - If some tree cannot be reached, return -1. Otherwise add the distance and move to the tree's cell.
Two details matter. Trees do not block us: we can walk through any non-zero cell, cut or not, so the BFS only avoids 0 cells. And the walk starts at (0, 0) even if a tree stands there; that tree is reached in 0 steps when its turn comes, as in Example 3.
Mark a cell as seen when it is put in the queue, not when it is taken out, so each cell is queued at most once per search.
Complexity: O(t · m · n + t log t) time and O(m · n) space, where the forest is m x n and t is the number of trees: each of the t searches visits at most m · n cells.
import collections
class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
rows, cols = len(forest), len(forest[0])
def steps(start_r: int, start_c: int, target_r: int, target_c: int) -> int:
"""Fewest steps between two cells (BFS), or -1 if the target cannot be reached."""
if (start_r, start_c) == (target_r, target_c):
return 0
seen = [[False] * cols for _ in range(rows)]
seen[start_r][start_c] = True
queue = collections.deque([(start_r, start_c, 0)])
while queue:
r, c, dist = 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 not seen[nr][nc] and forest[nr][nc] != 0:
if (nr, nc) == (target_r, target_c):
return dist + 1
seen[nr][nc] = True
queue.append((nr, nc, dist + 1))
return -1
# Trees in the order they must be cut: shortest first.
trees = sorted((forest[r][c], r, c) for r in range(rows) for c in range(cols) if forest[r][c] > 1)
total = 0
cur_r, cur_c = 0, 0
for _, r, c in trees:
dist = steps(cur_r, cur_c, r, c)
if dist == -1:
return -1
total += dist
cur_r, cur_c = r, c # we now stand where the tree was
return total
Now write it from memory
Close the write-up and solve it yourself against the tests.