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
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.