No of paths from top left to bottom right in a Matrix Linked to the concept of Longest Common Subsequence

Count all possible paths from top left to bottom right
The task is to count all the possible paths from top left to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or down.
Input: 
First line consists of T test cases. First line of every test case consists of N and M, denoting the number of rows and number of column respectively.
Output: 
Single line output i.e count of all the possible paths from top left to bottom right of a mXn matrix. Since output can be very large number use %10^9+7.
Constraints:
1<=T<=100
1<=N<=100
1<=M<=100
Example:
Input:

1
3 3
Output:
6



#include <iostream>


using namespace std;


int path(int m , int n)
{ int a[m][n];

// now we want to find the total paths from left top to bottom right
//we use the concept of longest common subsequence to do it
//in l.c.s we check if a[i]==a[j]
// if true then done add 1 to diagnol element else copy max(left,top)
// but here concept is little different
//if(i||j=0)make that r/c as all 1
// now for every elemnt grid i,j will have the sum of its top+its immediate left

for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||j==0)
{
a[i][j]=1;
}
else
{
a[i][j]=a[i-1][j]+a[i][j-1];

}

}

}

return a[m-1][n-1];
}


int main() {

int t,m,n;
cin>>t;
while(t--)
{
cin>>m>>n;
cout<<path(m,n);
cout<<endl;
}
}

Comments

Popular posts from this blog

Linked List 10 operations from which problems are made ( complete guide for you)

Stack - print bracket number