Possible Paths from Top Left to Bottom Right of a Matrix in Java
In this section, we will learn about finding the possible paths from top left to bottom right of a matrix in Java. It is one of the prominent problems asked in the interview. The constraint to go from top left to bottom right is that from any cell, one can move in the rightward (→) or in the downward direction (↓). Let's see a few examples for better understanding.
Note: Readers are advised to learn the arrays and recursion first, then go through this topic.
In the above 3 * 3 matrix, one has to go from cell marked as 1 to the cell marked as 5. From cell 1, one can either go cell 4 or the cell 7. Similarly, from cell 4, one can go the cell 8 or cell 2, and from cell 7, one can go cell 6 or cell 8. Thus, continuing in the same manner, one will get the following.
Thus, we see that there are 6 ways to reach the cell marked as 5 from the cell marked as 1.
In the above 2 * 4 matrix, one will get the following.
Thus, we see that there are 4 ways to reach the cell marked as 9 from the cell marked as 2.
Simple recursion will be enough to solve the problem. First of all, we display all the paths while going in the downward direction, and after that, we display all the paths while going in the rightward direction. We will be doing it recursively for each cell that is encountered in the path.
The following is the implementation for printing the possible paths from the top left to the bottom right of a matrix.
For the matrix: 1 4 2 7 8 0 6 3 5 The possible paths from the top left to the bottom right is: [1, 7, 6, 3, 5] [1, 7, 8, 3, 5] [1, 7, 8, 0, 5] [1, 4, 8, 3, 5] [1, 4, 8, 0, 5] [1, 4, 2, 0, 5]
We can also solve this problem using iteration. In this approach, we will be using Breadth-First Search (BFS). A queue will be used that will contain the cell coordinates and paths up to the certain cell. From the top-left cell, we will start pushing the coordinates and the value of the cell into the queue (the value of the cell is stored in a vector). We will continue to explore the down and right cells unless the queue is not empty and will also continue to push the undiscovered cells in the queue. When we reach the bottom-right cell of the matrix, then the vector containing the values of the cells explored is our answer.
For the following matrix: [1, 4, 2] [7, 8, 0] [6, 3, 5] The possible paths from the top left to the bottom right is: 1 4 2 0 5 1 4 8 0 5 1 4 8 3 5 1 7 8 0 5 1 7 8 3 5 1 7 6 3 5