Given an M × N rectangular grid, print all routes in the grid that start at the first cell (0, 0) and ends at the last cell (M-1, N-1). We can move down or right or diagonally (down-right), but not up or left.

For example,

Input:
 
{ 1, 2, 3 }
{ 4, 5, 6 }
{ 7, 8, 9 }
 
Output:
 
[ 1, 4, 7, 8, 9 ]
[ 1, 4, 5, 8, 9 ]
[ 1, 4, 5, 6, 9 ]
[ 1, 4, 5, 9 ]
[ 1, 4, 8, 9 ]
[ 1, 2, 5, 8, 9 ]
[ 1, 2, 5, 6, 9 ]
[ 1, 2, 5, 9 ]
[ 1, 2, 3, 6, 9 ]
[ 1, 2, 6, 9 ]
[ 1, 5, 8, 9 ]
[ 1, 5, 6, 9 ]
[ 1, 5, 9 ]

Practice this problem

The idea is to use recursion to find all routes. Start from the source cell (top-left corner) of the grid and recur for the next nodes. The next node can be either of the immediate right cell, immediate bottom cell, or immediate down-right diagonal cell. Recursively repeat this for every visited cell until the destination is reached. Also, maintain a data structure to store nodes in the current route and print the path whenever the destination cell (bottom-right corner) is reached.

Here’s code to print all such paths in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
[1, 4, 7, 8, 9]
[1, 4, 5, 8, 9]
[1, 4, 5, 6, 9]
[1, 4, 5, 9]
[1, 4, 8, 9]
[1, 2, 5, 8, 9]
[1, 2, 5, 6, 9]
[1, 2, 5, 9]
[1, 2, 3, 6, 9]
[1, 2, 6, 9]
[1, 5, 8, 9]
[1, 5, 6, 9]
[1, 5, 9]

The time complexity of the proposed solution is exponential.

T(M, N) = T(M, N-1) + T(M-1, N) + T(M-1, N-1)
T(M, 1) = M
T(1, N) = N
T(1, 1) = 1

The additional space required by the program is O(M + N).

 
There is another variation of the above problem where we need to print only those paths above the diagonal x = y. For example, the following paths are valid for the above matrix:

[1, 2, 3, 6, 9]
[1, 2, 5, 6, 9]
[1, 2, 5, 9]
[1, 2, 6, 9]
[1, 5, 6, 9]
[1, 5, 9]

For a path to be valid, at all points (x, y) on the path, x should be less than y. We can simply enforce this constraint while building the paths. This is demonstrated below in C++, Java, and Python:

C++, Java, and Python code.

 
Exercise: Efficiently count the total number of possible paths in a matrix from the top-left corner to the bottom-right corner using dynamic programming.