Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of longest possible route possible from source to destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contains any diagonal moves and a location once visited in a particular path cannot be visited again.
For example, longest path with no hurdles from source to destination is highlighted for below matrix. The length of the path is 24.
The idea is to use Backtracking. We start from the source cell of the matrix, move forward in all four allowed directions and recursively checks if they leads to the solution or not. If destination is found, we update the value of longest path else if none of the above solutions work we return false from our function.
Below is C++ implementation of above idea –
Length of longest possible route is 24
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find shortest safe route in a path with landmines
- Check if it is possible to make the given matrix increasing matrix or not
- Maximum trace possible for any sub-matrix of the given matrix
- Find the longest path in a matrix with given constraints
- Longest Increasing Path in Matrix
- Print all possible paths from top left to bottom right of a mXn matrix
- Count all possible paths from top left to bottom right of a mXn matrix
- Check if possible to cross the matrix with given power
- Check for possible path in 2D matrix
- Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
- Check if possible to shuffle a matrix with adjacent movements
- Maximum Sum possible by selecting X elements from a Matrix based on given conditions
- Check if it is possible to create a matrix such that every row has A 1s and every column has B 1s
- Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Count frequency of k in a matrix of size n where matrix(i, j) = i+j
- Program to check diagonal matrix and scalar matrix
- Program to check if a matrix is Binary matrix or not