Minimum Cost Path

You have been given a matrix of ‘N’ rows and ‘M’ columns filled up with integers. Find the minimum sum that can be obtained from a path which from cell (x,y) and ends at the top left corner (1,1).

From any cell in a row, we can move to the right, down or the down right diagonal cell. So from a particular cell (row, col), we can move to the following three cells:

Down: (row+1,col)
Right: (row, col+1)
Down right diagonal: (row+1, col+1)
Input Format:
The first line will contain two integers ‘N’ and ‘M’ denoting the number of rows and columns, respectively.

Next ‘N’ lines contain ‘M’ space-separated integers each denoting the elements in the matrix.

The last line will contain two integers ‘x’ and ‘y’ denoting the cell to start from.
Output Format:
For each test case, print an integer that represents the minimum sum that can be obtained by traveling a path as described above.

Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 50
1 <= N, M <= 100
-10000 <= cost[i][j] <= 10000
1 <= x, y <= 100

Time limit: 1 sec
CodingNinjas
author
2y
Recursive Approach

Let’s start from cell (X,Y). There are 3 possible cells from which we can come to (X,Y) (assuming they don’t violate the bounds of the array): cells (X-1, Y), (X, Y-1) and (X-1, Y-1)...read more

CodingNinjas
author
2y
Memoization Method

If you draw the recursion tree of all the function calls, you notice that the results of some cells get computed repeatedly. Instead of recomputing it, again and again, we instead st...read more

CodingNinjas
author
2y
Iterative DP Approach

For each cell, let’s compute the answer in a top-down fashion, starting from the top leftmost cells. We create a ‘dp’ table of dimensions X*Y to store these results.

As we comput...read more

Add answer anonymously...
Cisco Consultant Engineer 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