Min Jumps

You live in a Ninja town which is in the form of a N * M grid. In this town, people travel from one place to another by jumping over the buildings which are present in each cell of the grid. It is Christmas eve, and Santa wants to give gifts and chocolates to the kids who live in the building which is present at the cell (N - 1, M - 1). Initially, Santa is present on cell (0, 0). Since Santa is in a hurry, help him find a path from starting point to the endpoint with the least amount of time.

The Santa may go only from one building to any of its adjacent buildings which is present either to the right or to the bottom or bottom right cell i.e. if the current position is (x, y), he may go to (x + 1, y + 1) or (x + 1, y) or (x, y + 1) given that the new coordinates are in the grid. The time taken to reach from one building to another is equal to the absolute difference between the heights of buildings.

Note:

1. The heights of the buildings are positive.
2. Santa starts from the cell (0, 0) and he has to reach the building (N - 1, M - 1).
3. Santa cannot leave the grid at any point of time.
Input Format:
The first line of the input contains an integer T denoting the number of test cases. Then T lines follow:

The first line of each test case contains two space-separated integers N and M, where N = number of rows in the given matrix and M = number of columns in the given matrix.    

Then N lines follow for each test case:
Each line contains M space-separated integers.

For more clarity please refer to the sample input.
Output Format:
The only line of output of each test case consists of an integer X, denoting the minimum time required to reach the last cell.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^2
1 <= N <= 10^2
1 <= M <= 10^2
1 <= Height <= 10^5

Time Limit: 1sec
CodingNinjas
author
2y
Recursive
  1. Since we want to try all the possible combinations and then find the answer, recursion is a good way to do it.
  2. Let the name of the given matrix be ARR[][] where ARR[X][Y] denotes the height of...read more
CodingNinjas
author
2y
Dynamic Programming
  1. Since the complexity of the recursive approach is exponential, we will have to optimize it using dynamic programming. We can apply dynamic programing because,
  2. Let the 2D array be DP[...read more
Help your peers!
Add answer anonymously...
Tata CLiQ 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
Get AmbitionBox app

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