Path in Matrix-dynamic programming
this sum is taken from geeks for geeks :
if u want to solve this go to the link:
https://practice.geeksforgeeks.org/problems/path-in-matrix/0
Given a N X N matrix Matrix[N][N] of positive integers. There are only three possible moves from a cell Matrix[r][c].
1. Matrix[r+1][c]
2. Matrix[r+1][c-1]
3. 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.
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.
Example:
Input:
1
2
348 391 618 193
Output:
1009
Explanation: In the sample test case, the path leading to maximum possible sum is 391->618. (391 + 618 = 1009)
lets use dynamic programming to solve this question:
c++ implementation:
t is the no.of test cases:
if u want to solve this go to the link:
https://practice.geeksforgeeks.org/problems/path-in-matrix/0
Given a N X N matrix Matrix[N][N] of positive integers. There are only three possible moves from a cell Matrix[r][c].
1. Matrix[r+1][c]
2. Matrix[r+1][c-1]
3. 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.
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.
Example:
Input:
1
2
348 391 618 193
Output:
1009
Explanation: In the sample test case, the path leading to maximum possible sum is 391->618. (391 + 618 = 1009)
lets use dynamic programming to solve this question:
c++ implementation:
t is the no.of test cases:
#include <bits/stdc++.h>
using namespace std;
int main() { int t; cin>>t;
while(t--)
{
int n; cin>>n;
int a[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(i==0)
a[i][j]=a[i][j];
else if(j==0 && i!=0)
a[i][j]=a[i][j]+max(a[i-1][j],a[i-1][j+1]);
else if(j==n-1 && i!=0)
a[i][j]=a[i][j]+max(a[i-1][j],a[i-1][j-1]);
else{
int x=max(a[i-1][j],a[i-1][j-1]);
a[i][j]=a[i][j]+max(x,a[i-1][j+1]);}
}
}
int maxele=a[n-1][0];
for(int j=1;j<n;j++)
maxele=max(maxele,a[n-1][j]);
cout<<maxele;
cout<<endl;
}
//code
return 0;
}