Given an M × N integer matrix, find all paths from the first cell to the last cell. We can only move down or to the right from the current cell.

For example,

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

Practice this problem

We can easily solve this problem by using recursion. The idea is to start from the top-left cell of the matrix and recur for the next node (immediate right or immediate bottom cell) and keep on doing that for every visited cell until the destination is reached. Also maintain a path array to store the nodes in the current path and update the path array (including the current node) whenever any cell is visited. Now, whenever the destination (bottom-right corner) is reached, print the path array.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1, 2, 3, 6, 9
1, 2, 5, 6, 9
1, 2, 5, 8, 9
1, 4, 5, 6, 9
1, 4, 5, 8, 9
1, 4, 7, 8, 9

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

The time complexity of the proposed solution is exponential.

T(M, N) = T(M, N-1) + T(M-1, N)        // for two recursive calls
T(M, 1) = M, T(1, N) = N, T(1, 1) = 1

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

 
If we carefully analyze the solution, we can see the problem has overlapping subproblems. So, it can be solved using dynamic programming, and time complexity can be reduced drastically (space complexity will also increase drastically).

 
Exercise:

1. Modify the proposed solution to DP using memoization.
2. Convert the code to C using an array for storing path information.