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.
- Find shortest safe route in a path with landmines
- Longest Increasing Path in Matrix
- Find the longest path in a matrix with given constraints
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- Check if matrix can be converted to another matrix by transposing square sub-matrices
- Program to check diagonal matrix and scalar matrix
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- C++ program to Convert a Matrix to Sparse Matrix
- Program to check if a matrix is Binary matrix or not
- Check if it is possible to make the given matrix increasing matrix or not
- Count frequency of k in a matrix of size n where matrix(i, j) = i+j
- Program to convert given Matrix to a Diagonal Matrix