Task: Find the maximum path sum from given N*N matrix, Start from any column in row 0, move in three paths from current position Matrix[r][c] to Matrix[r+1][c] or Matrix[r+1][c-1] or Matrix[r+1][c+1] up to row N-1.
Example:
Input:
1
2
348 391 618 193
Output:
1009 // 391 + 618
Here is the Code:
Program in C++:
- #include<iostream>
- 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];
- }
- }
- int dp[n][n];
- for(int i=0;i<n;i++)
- {
- dp[0][i]=a[0][i];
- }
- for(int i=1;i<n;i++)
- {
- for(int j=0;j<n;j++)
- {
- if(j==0)
- {
- dp[i][j]=a[i][j]+max(dp[i-1][j],dp[i-1][j+1]);
- }
- else if(j==n-1)
- {
- dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
- }
- else
- {
- int t = max(dp[i-1][j-1],dp[i-1][j]);
- dp[i][j]=a[i][j]+max(t,dp[i-1][j+1]);
- }
- }
- }
- int max=dp[n-1][0];
- for(int i=0;i<n;i++)
- {
- if(max<dp[n-1][i])
- {
- max=dp[n-1][i];
- }
- }
- cout<<max<<endl;
- }
- return 0;
- }
- // Updated Version
- class Solution{
- public:
- int maximumPath(int N, vector<vector<int>> a)
- {
- // code here
- int dp[N][N];
- for(int i=0;i<N;i++)
- {
- dp[0][i]=a[0][i];
- }
- for(int i=1;i<N;i++)
- {
- for(int j=0;j<N;j++)
- {
- if(j==0)
- {
- dp[i][j]=a[i][j]+max(dp[i-1][j],dp[i-1][j+1]);
- }
- else if(j==N-1)
- {
- dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
- }
- else
- {
- int t = max(dp[i-1][j-1],dp[i-1][j]);
- dp[i][j]=a[i][j]+max(t,dp[i-1][j+1]);
- }
- }
- }
- int max=dp[N-1][0];
- for(int i=0;i<N;i++)
- {
- if(max<dp[N-1][i])
- {
- max=dp[N-1][i];
- }
- }
- return max;
- }
- };
Here is the Video:
Comments
Post a Comment