You are given an ‘M*N’ Matrix, You need to print all possible paths from its top left corner to the bottom right corner if given that you can either move right i.e from (i,j) to (i,j+1) or down i.e from (i, j) to (i+1, j).
For Example :1 2 3
4 5 6
For the above 2*3 matrix , possible paths are (1 2 3 6) , (1 2 5 6) , (1 4 5 6).
Note :
You can return the paths in any order.
The first line contains two space-separated integers, ‘M’ and ‘N’ denoting the number of rows and columns of the given matrix.
Each of the following ‘M’ lines contains N space-separated numbers.
Output Format :
Print all the paths in a new line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= M, N <= 10
Time Limit: 1 sec
2 2
1 2
3 4
1 3 4
1 2 4
All the possible paths on moving right and down are (1 3 4) and (1 2 4).
3 2
5 10
15 20
25 30
5 15 25 30
5 15 20 30
5 10 20 30
Can we use recursion to generate all the paths?
The basic idea to solve this problem is to use recursion. Recursively call function for next row ( row+1,col ) and next column ( row, col+1 ). If the row is equal to M-1 or the column is equal to N-1, then recursion is stopped.
Algorithm:
Let us understand the above approach with the help of a recursion tree for the matrix given below
1 2 3
4 5 6
Output: 1 4 5 6
1 2 5 6
1 2 3 6
O(2^(M+N)), where M is the number of rows and N is the number of columns.
The minimum length from root to a leaf node in the recursion tree is min(M, N) and the maximum length is M+N. Therefore the total number of nodes is between 2^min(M, N) and 2^(M+N). Hence time complexity is O(2^(M+N)).
O(M+N).
Extra space used to store the path.