Objective: Given two dimensional matrix, write an algorithm to count all possible paths from top left corner to bottom-right corner. You are allowed to move only in two directions, move right OR move down.

From every cell you will have two options to make a move, either to go right OR down. Base case will be check if you have reached to either last row OR last column then there is only one way to reach the last cell is to travel through that row or column. x

Recursive Code:

Time Complexity: It will be exponential since we are solving many sub problems repeatedly. We will use the Bottom-up approach of Dynamic programming and store the results of sub problems to reuse them in future.

Dynamic Programming Code:

Output:

No Of Path (Recursion):- 6
No Of Path (DP):- 6

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

The simple “proof” is this: You have to go across (move to the right) exact column-1 times and you have to move downward exactly row-1 times. (-1 because you don’t count the starting cell)

So it’s back a simple combinatorial math problem of having choosing x elements and y elements to make a (x+y) series.

Sivaram

I came across an interview question which is similar to this problem.
A point P(x,y) is given. This point represents the coordinates in the matrix.
Then count all the paths from top left to the given point and from that point to bottom right corner of the matrix.
Could you please explain how to approach this problem.
I thought it would be two sub problems of this problem.
Firstly count all paths from top left to the given point using this approach.
Then start from the given point and count the paths to the bottom right corner of the matrix using the same approach.

Could you advise if this is better way or is there a more neat solution?