Skip to main content

Posts

Showing posts with the label Path in Matrix

Path in Matrix

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-