1068. Cut Off Trees for Golf Event

MediumGraphsGridBFSGraph

Given a forest grid where 0 is impassable, 1 is walkable ground, and any value > 1 is a tree of that height, you must cut all trees in strictly increasing height order, starting from the top-left cell, moving 4-directionally through non-zero cells. Return the total number of steps walked, or -1 if some tree cannot be reached. The input is JSON {forest}.

Input: JSON {forest}.

Output: Integer — total steps, or -1.

Examples

Example 1
Input: {"forest":[[1,2,3],[0,0,4],[7,6,5]]}
Output: 6
Explanation: Walk to each tree in height order.
Example 2
Input: {"forest":[[1,2,3],[0,0,0],[7,6,5]]}
Output: -1
Explanation: A tree is unreachable.
Example 3
Input: {"forest":[[2,3,4],[0,0,5],[8,7,6]]}
Output: 6
Explanation: Reachable in order.

Constraints

Asked by

FlipkartAmazon
Solve this problem in the editor →