Path in Matrix

PROBLEM :
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.

Constraints:
1<=T<=20
2<=N<=20
1<=Matrix[i][j]<=1000 (for all 1<=i<=N && 1<=j<=N)

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)

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<limits.h>
#define max 20
int Path_in_Matrix(int [max][max],int ) ;
int max_of1(int ,int ) ;
int max_of2(int ,int ,int ) ;

int main()
 {
int t,no,i,j ;
int mat[max][max] ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       for(j=0;j<no;j++)
           cin>>mat[i][j] ;
         
   cout<<Path_in_Matrix(mat,no)<<endl ;
}
return 0;
}

int Path_in_Matrix(int mat[max][max],int no)
{
    int i,j,big ;
    big=INT_MIN ;
   
    for(i=1;i<no;i++)
    {
        for(j=0;j<no;j++)
        {
            if(j==0)
                mat[i][j]+=max_of1(mat[i-1][j],mat[i-1][j+1]) ;
            else if(j==no-1)
                mat[i][j]+=max_of1(mat[i-1][j],mat[i-1][j-1]) ;
            else
                mat[i][j]+=max_of2(mat[i-1][j],mat[i-1][j+1],mat[i-1][j-1]) ;
        }
    }
   
    for(i=0;i<no;i++)
        big=big>mat[no-1][i]?big:mat[no-1][i] ;
   
    return big ;
}

int max_of1(int a,int b)
{
    return a>b?a:b ;
}

int max_of2(int a,int b,int c)
{
    int temp ;
    temp=a>b?a:b ;
    return temp>c?temp:c ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )