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

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.
Run ⌘' · Submit ⌘⏎