Longest Possible Route in a Matrix with Hurdles
Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location once visited in a particular path cannot be visited again.
For example, the longest path with no hurdles from source to destination is highlighted below. 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 lead to the solution or not. If the destination is found, we update the value of the longest path else if none of the above solutions work we return false from our function.
Below is the implementation of the above idea –
Length of longest possible route is 24
Time Complexity: 4^(R*C)
Here R and C are the numbers of rows and columns respectively. For every index we have four options, so our overall time complexity will become 4^(R*C).
Auxiliary Space: O(R*C)
The extra space is used in storing the elements of the visited matrix.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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.