Given an M × N matrix, count the number of different ways to reach the bottom-right corner of a matrix from its top-left corner with exactly k turn allowed and using only the directions right or down.

A turn is defined as a down move immediately followed by a right move, or a right move immediately followed by a down move.

For example, consider a 3 × 3 matrix.

 
3×3 matrix

Input:  k = 1
Output: Total number of paths are 2
 
(0, 0) —> (0, 1) —> (0, 2) —> (1, 2) —> (2, 2)
(0, 0) —> (1, 0) —> (2, 0) —> (2, 1) —> (2, 2)
 
 
Input:  k = 2
Output: Total number of paths are 2
 
(0, 0) —> (0, 1) —> (1, 1) —> (2, 1) —> (2, 2)
(0, 0) —> (1, 0) —> (1, 1) —> (1, 2) —> (2, 2)
 
 
Input:  k = 3
Output: Total number of paths are 2
 
(0, 0) —> (0, 1) —> (1, 1) —> (1, 2) —> (2, 2)
(0, 0) —> (1, 0) —> (1, 1) —> (2, 1) —> (2, 2)
 
Input:  k = 4
Output: Total number of paths are 0

Practice this problem

We can recursively solve this problem. The idea is to keep track of the current direction and number of turns so far. If the current direction is along a column, we have two options for the next move – continue moving along the column, or turn right and decrement the number of turns by 1. Similarly, if the current direction is along a row, continue moving in the same direction, or turn down and decrement the number of turns by 1. A path is found if the destination is reached with exactly k turns.

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

C++


Download  Run Code

Output:

The total number of paths is 2

Java


Download  Run Code

Output:

The total number of paths is 2

Python


Download  Run Code

Output:

The total number of paths is 2

The time complexity of the proposed solution is exponential since it recomputes the same subproblem repeatedly. We can easily optimize the code to run in O(M × N × k) time with dynamic programming. The idea is to store the results of function calls and return the cached result when the same input occurs again.

 
Exercise:

1. Implement a dynamic programming solution using memoization.
2. Modify the solution for at most k turns.