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]
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
- 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
- Count of palindromic plus paths in a given Matrix
- 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
- Total number of decreasing paths in a matrix
- Sum of cost of all paths to reach a given cell in a Matrix
- Print all paths from a given source to a destination