Skip to content
DeepForgeby svx
All problems
HardAlgorithmsal-253

Cut Off Trees for Golf Event

Problem

Given a forest grid where 0 is blocked, 1 is grass and any value above 1 is a tree, return the minimum steps to cut all trees in increasing height order starting from (0, 0), or -1 if a tree is unreachable.

Sort the trees by height and run a BFS for each consecutive pair, computing the distance from the previously cut tree. Sum the distances.

Hint

Grass cells are walkable, so only zeros block the BFS.

Test cases

case 1
in: [[[1,2,3],[0,0,4],[7,6,5]]]
expected: 6
case 2
in: [[[1,2,3],[0,0,0],[7,6,5]]]
expected: -1
case 3
in: [[[2,3,4],[0,0,5],[8,7,6]]]
expected: 6
case 4
in: [[[1]]]
expected: 0
Starter codePython
def cut_off_trees_shortest(forest):
    # Your code here
    pass

4 test cases · run your code against them in the editor