The problem is to print all the possible paths from top left to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or down.
Input : 1 2 3 4 5 6 Output : 1 4 5 6 1 2 5 6 1 2 3 6 Input : 1 2 3 4 Output : 1 2 4 1 3 4
The algorithm is a simple recursive algorithm, from each cell first print all paths by going down and then print all paths by going right. Do this recursively for each cell encountered.
Following are implementation of the above algorithm.
1 4 5 6 1 2 5 6 1 2 3 6
Note that in the above code, the last line of printAllPathsUtil() is commented, If we uncomment this line, we get all the paths from the top left to bottom right of a nXm matrix if the diagonal movements are also allowed. And also if moving to some of the cells are not permitted then the same code can be improved by passing the restriction array to the above function and that is left as an exercise.
This article is contributed by Hariprasad NG. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
[1, 4, 7, 8, 9] [1, 4, 5, 8, 9] [1, 4, 5, 6, 9] [1, 2, 5, 8, 9] [1, 2, 5, 6, 9] [1, 2, 3, 6, 9]
- Print all palindromic paths from top left to bottom right in a matrix
- Print all paths from top left to bottom right in a matrix with four moves allowed
- Count all possible paths from top left to bottom right of a mXn matrix
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Maximum points from top left of matrix to bottom right and return back
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Minimum cost to reach from the top-left to the bottom-right corner of a matrix
- Print a matrix in alternate manner (left to right then right to left)
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- Maximum sum path in a matrix from top to bottom
- Maximum sum path in a matrix from top to bottom and back
- Number of palindromic paths in a matrix
- Print all possible paths from the first row to the last row in a 2D array
- Maths behind number of paths in matrix problem