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.