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 height X > 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 and M, the dimensions of FOREST.
  • N subsequent lines each containing M space-separated integers defining the FOREST 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.

Be the first one to answer
Add answer anonymously...
Tower Research Capital LLC Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter