Cut Off Trees for Golf Event

Hard · Trees · Array · Breadth-First Search · Heap (Priority Queue) · Matrix

Problem

A forest is given as an m x n grid forest:

You start at (0, 0) and may move one cell north, south, east or west per step. You must cut down all trees in order from shortest to tallest. Standing on a tree's cell lets you cut it, after which the cell becomes 1. You may walk over a tree without cutting it. No two trees have the same height, and there is at least one tree.

Return the minimum number of steps needed to cut every tree, or -1 if some tree cannot be reached.

Examples

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

You start on the height-2 tree and then walk the ring past 3, 4, 5, 6, 7, 8, one step each.

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

The row of obstacles cuts off the bottom trees.

Input: forest = [[1,4,1],[2,0,3]]
Output: 7

Down to 2 (1 step), back up and across to 3 (4 steps), then back to 4 (2 steps): 7.

Constraints

Approaches

Follow-up

With fixed legs, each leg could also use A* with the Manhattan distance as its guide, which explores fewer cells on open ground. The use cases return the length of every leg, and count the reachable trees with a single flood fill.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…