VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-possible-route-in-a-matrix-with-hurdles/

⇱ Longest Possible Route in a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Possible Route in a Matrix

Last Updated : 17 Nov, 2025

Given a 2D binary matrix mat[][] where 0 represent hurdle and 1 free cell. Find the length of the longest path from a source (xs, ys) to a destination (xd, yd) with these rules:

  • Move only up, down, left, or right (no diagonals).
  • Each cell can be visited at most once in a path.
  • If reaching the destination is impossible, return -1.

Examples:

Input: xs = 0, ys = 0, xd = 1, yd = 7
mat[][] = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
Output: 24
Explanation:

👁 420046962

Input: xs = 0, ys = 3, xd = 2, yd = 2
mat[][] =[ [1, 0, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]
Output: -1
Explanation: We can see that it is impossible to reach the cell (2,2) from (0,3).

[Approach] Using Backtracking with Visited Matrix - O(4(m*n)) Time and O(m*n) Space

The idea is to use backtracking. We start from the source cell and recursively explore all four allowed directions—up, down, left, and right while keeping track of the cells already visited using a visited array. For each move, we mark the current cell as visited and continue exploring valid adjacent cells. If we reach the destination, we update the length of the longest path found so far. After exploring a path, we backtrack by unmarking the cell in the visited array so it can be used in other paths.


Output
24

[Optimized Approach] Without Using Extra Space - O(4(m*n)) Time and O(1) Space

Instead of using a separate visited matrix, mark cells as visited directly in the input matrix by setting them to 0. Explore all four directions recursively. After finishing a path from a cell, restore its value to 1 (backtracking).


Output
24


Comment