Clearing the Forest Problem Statement
Ninja lives in a city called Byteland where a festive event is being organized. To make space for this event, Ninja is tasked with clearing a nearby forest. The forest is represented as an N
*M
grid called FOREST
, where each cell has:
0
: The cell is empty; Ninja can pass through it.'X'
: A tree with heightX > 0
; Ninja can pass through it.-1
: The cell is not accessible.
Ninja starts at the top-left corner cell(0, 0)
and must cut down all trees, moving in any of the four cardinal directions per step. Trees must be cut in order from shortest to tallest, turning the cell into 0
after cutting. Ninja also has the option to pass through a tree cell without cutting it. No two trees have the same height, and there is at least one tree to cut.
Your task is to calculate the minimum number of steps Ninja needs to cut down all trees. If it's impossible to cut all trees, return -1
.
Input:
The first line contains an integer T
denoting the number of test cases. For each test case:
- An integer line with
N
andM
, the dimensions ofFOREST
. N
subsequent lines each containingM
space-separated integers defining theFOREST
grid.
Output:
For each test case, output a single integer representing the minimum steps to cut all trees, or -1
if not possible. Each result is on a new line.
Example:
Input:
1
3 3
1 2 0
-1 5 -1
0 6 7
Output:
4
Constraints:
1 ≤ T ≤ 10
1 ≤ N, M ≤ 50
-1 ≤ FOREST[i][j] ≤ 10^5
- Time limit: 1 second
Note:
No printing is needed; just implement the function to return the required answer.
Top Tower Research Capital LLC Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month