Given an M × N rectangular grid, efficiently count all paths starting from the first cell (0, 0) to the last cell (M-1, N-1). We can either move down or move towards right from a cell.

For example,

Input:  3 × 3 matrix
 
Output: Total number of paths are 6
 
(0, 0) —> (0, 1) —> (0, 2) —> (1, 2) —> (2, 2)
(0, 0) —> (0, 1) —> (1, 1) —> (1, 2) —> (2, 2)
(0, 0) —> (0, 1) —> (1, 1) —> (2, 1) —> (2, 2)
(0, 0) —> (1, 0) —> (2, 0) —> (2, 1) —> (2, 2)
(0, 0) —> (1, 0) —> (1, 1) —> (1, 2) —> (2, 2)
(0, 0) —> (1, 0) —> (1, 1) —> (2, 1) —> (2, 2)

Practice this problem

The idea is to start from the top-left corner of the matrix and recur for the next cell, which can be either the immediate right cell or the immediate bottom cell. We can easily maintain the path count as we move along in the recursion, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The total number of paths is 6

Java


Download  Run Code

Output:

The total number of paths is 6

Python


Download  Run Code

Output:

The total number of paths is 6

The time complexity of the proposed solution is exponential since it exhibits overlapping subproblems, i.e., it computes solutions to the same subproblems repeatedly. The problem also has an optimal substructure as the solution to the problem can be derived using a solution to its subproblems. Since both dynamic programming properties are satisfied, we can use it to optimize the code.

We can either store results of the function calls and return those results when the same input occurs again or construct an auxiliary matrix to store results of the smaller subproblems. The following code follows the later approach:

C


Download  Run Code

Output:

The total number of paths is 6

Java


Download  Run Code

Output:

The total number of paths is 6

Python


Download  Run Code

Output:

The total number of paths is 6

The time complexity of the proposed solution is O(M × N) for an M × N matrix. The auxiliary space required by the program is O(M × N). The space complexity of the solution can be improved up to O(N) as we are only reading data of the previous row for filling the current row. Following is the space-optimized solution using only a single array:

C


Download  Run Code

Output:

The total number of paths is 6

Java


Download  Run Code

Output:

The total number of paths is 6

Python


Download  Run Code

Output:

The total number of paths is 6

We can also find the number of paths from the first cell (0, 0) to the last cell (M-1, N-1) using a direct formula. To reach the last cell, we have to take m-1 steps to the right and n-1 steps down. So, the total steps are (m-1)+(n-1) = m+n-2. Out of these (m+n-2) steps, any n-1 steps can be down, and any m-1 steps can be towards the right. So, the total number of ways are (m+n-2)C(n-1) or (m+n-2)C(m-1).

 
Exercise: Extend the solution for diagonal moves (down-right).

 
Suggested Post:

Find all paths from the first cell to the last cell of a matrix