

Down: (row+1,col)
Right: (row, col+1)
Down right diagonal: (row+1, col+1)
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case 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.
For each test case, print an integer which represents the minimum sum that can be obtained by travelling a path as described above.
Output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of.
1 <= T <= 50
1 <= N, M <= 100
-10000 <= cost[i][j] <= 10000
Where ‘T’ is the number of test cases.
Where 'N' is the number of rows in the given matrix, and 'M' is the number of columns in the given matrix.
And, cost[i][j] denotes the value at (i,j) cell in the matrix.
Time limit: 1 sec
The basic idea is to explore all possible paths recursively and return the minimum path sum among them. Steps are as follows:
The approach mentioned above can be formalised in the following manner.
Let minPathSum(row, col) is a function which returns the minimum path sum which can be obtained while moving from (row, col) to (N-1, M-1).
minPathSum(row, col) = min( minPathSum(row+1, col), minPathSum(row, col+1), minPathSum(row+1, col+1) ) + cost[row][col] Let us try to analyse the recursive tree from the previous approach when ‘N’ = 3 and ‘M’ = 3.
After observing the tree, we’ll find that there are some redundant function calls which mean that there are some overlapping subproblems. The repetition of such sub-problems suggests that we can use dynamic programming to optimise our approach.
The key idea behind a dynamic programming approach is to use memoization, i.e. we’ll save the result of our sub-problem in a matrix so that it can be used later on.
Let dp[row][col] be our dynamic programming matrix to store the minimum path sum which starts from (row, col)th cell and ends at (N-1, M-1)th cell. It will help us to avoid redundant function calls. Steps are as follows:
The key idea behind this approach is to update the given cost[][] matrix itself instead of using a “dp” matrix.
We will iterate through each row of the cost[][] matrix and will update the value of the (row, col)th element with the minimum path sum from (0, 0) to (row, col).
i.e. cost[row][col] = min(cost[row-1][col], cost[row][col-1] , cost[row-1][col-1]) + cost[row][col]4. If the current cell is the bottom right corner (N-1, M-1), we’ll stop our iterative process.
Since, cost[row-1][col-1] now represents the minimum path sum from (0, 0) to (row-1, col-1), cost[N-1][M-1] will be our answer.