Path in Matrix
Given a N X N Matrix, Matrix[N][N] of positive integers. There are only three possible moves from a cell Matrix[r][c].
- Matrix[r+1][c]
- Matrix[r+1][c-1]
- Matrix[r+1][c+1]
Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.
Problem description:
The problem wants you to find the path from any column of first row (0<=col<=N-1) to bottom-right corner of the matrix[N-1][N-1] such that the path you choose provide maximum value of sum during the traversal, the allowed movements are possible in only three direction as right, right-down and down.{(i,j)->(i+1,j+1),(i,j)->(i+1,j) and (i,j)->(i+1,j)}.
Input:
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the order of matrix. Next line contains N*N integers denoting the elements of the matrix in row-major form.
Output:
Output the largest sum of any of the paths starting from any cell of row 0 to any cell of row N-1. Print the output of each test case in a new line.
Examples:
Input:
T=1
N=3
1,2,3
4,5,6
7,8,9
Output:
18,
as moving from 3->6->9.
The problem can be solved with the help of a dynamic programming approach, in this approach we will create a cost 2-D array which will store the cost of visiting that cell.
Since we can move in only three direction from (i,j) that is we can move:
{i+1,j},{i+1,j+1} or {i+1,j-1},in other words we can reach the position {i,j} from three different position as:
{i,j}={i-1,j},{i-1,j+1},{i-1,j-1},we will use this approach and find the max cost for reaching index i,j from above given indices.
Here cost[i][j] is out cost function dp array and we will store input in dp[i][j] array.
So, our final dp state is as follow:
cost[i][j]=dp[i][j]+max(cost[i-1][j],cost[i-1][j+1],cost[i-1][j-1])
We need to keep in mind the index bound range before calculating it.
Since we need to find the maximum cost for reaching the last row, we will iterate through all columns of the last row for maximum value.
Time Complexity for the above approach in the worst case is: O(n*n)
Space Complexity for the above approach in the worst case is: O(n*n)
C++ Implementation:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer