Longest Possible Route in a Matrix with Hurdles

Pattern: Rat in a maze

medium

Explore every simple route from the source to the destination with backtracking, marking cells on the current route and unmarking them on the way back. Keep the largest number of moves among the routes that arrive.

The problem

A grid has open cells (1) and hurdles (0). Given a source and a destination cell, return the length (number of moves) of the longest route between them that moves up, down, left or right through open cells and never visits a cell twice, or -1 if there is no route. For example, the 3 × 10 grid of the GeeksforGeeks article from (0, 0) to (1, 7) gives 24.

The link above is a GeeksforGeeks article. The function name longestRoute(mat, sr, sc, dr, dc) is this guide's own.

Think first

  • Why does breadth-first search not help for "longest"?
  • Which cells must be off-limits during one route?
  • When is the answer -1?

Hints

    Brute force, and why it fails

    This is already the exhaustive method. Longest simple path has no known fast algorithm in general, so the grid must be small.

    The key insight

    The backtracking walk that lists every route (Rat in a Maze) also measures them. Keeping the maximum instead of a list answers the "longest" question.

    Dry run

    1 1 10 
    1 1 11 
    1 1 12 

    A 3 × 3 grid of open cells, from (0, 0) to (2, 2). The shortest route takes 4 moves, but we want the longest.

    Step 1 of 4

    The plan

    if source or destination is a hurdle: return -1
    best = -1; mark source
    function walk(r, c, steps):
        if (r, c) is the destination: best = max(best, steps); return
        for each open, unmarked neighbour: mark it; walk(it, steps + 1); unmark it
    walk(sr, sc, 0)
    return best
    

    Complexity

    Time
    O(4^(R × C)) worst
    Space
    O(R × C)

    Every simple route may be explored. Marks and recursion take O(R × C).

    Edge cases

    • Source equals destination: 0.
    • Blocked source or destination: -1.
    • No route: -1.
    I've built my logic, show the code

    Java

    class Solution {
        private int best;
    
        public int longestRoute(int[][] mat, int sr, int sc, int dr, int dc) {
            best = -1;
            if (mat[sr][sc] == 0 || mat[dr][dc] == 0) return -1;
            boolean[][] seen = new boolean[mat.length][mat[0].length];
            seen[sr][sc] = true;
            walk(mat, sr, sc, dr, dc, 0, seen);
            return best;
        }
    
        private void walk(int[][] m, int r, int c, int dr, int dc, int steps, boolean[][] seen) {
            if (r == dr && c == dc) { best = Math.max(best, steps); return; }   // reached: keep the longest
            int[] a = {0, 1, 0, -1}, b = {1, 0, -1, 0};
            for (int k = 0; k < 4; k++) {
                int nr = r + a[k], nc = c + b[k];
                if (nr < 0 || nc < 0 || nr >= m.length || nc >= m[0].length || m[nr][nc] == 0 || seen[nr][nc]) continue;
                seen[nr][nc] = true;
                walk(m, nr, nc, dr, dc, steps + 1, seen);
                seen[nr][nc] = false;                       // free it for other routes
            }
        }
    }

    C++

    class Solution {
    public:
        int best;
    
        int longestRoute(vector<vector<int>>& mat, int sr, int sc, int dr, int dc) {
            best = -1;
            if (mat[sr][sc] == 0 || mat[dr][dc] == 0) return -1;
            vector<vector<bool>> seen(mat.size(), vector<bool>(mat[0].size(), false));
            seen[sr][sc] = true;
            walk(mat, sr, sc, dr, dc, 0, seen);
            return best;
        }
    
        void walk(vector<vector<int>>& m, int r, int c, int dr, int dc, int steps, vector<vector<bool>>& seen) {
            if (r == dr && c == dc) { best = max(best, steps); return; }   // reached: keep the longest
            const int a[4] = {0, 1, 0, -1}, b[4] = {1, 0, -1, 0};
            int R = static_cast<int>(m.size()), C = static_cast<int>(m[0].size());
            for (int k = 0; k < 4; k++) {
                int nr = r + a[k], nc = c + b[k];
                if (nr < 0 || nc < 0 || nr >= R || nc >= C || m[nr][nc] == 0 || seen[nr][nc]) continue;
                seen[nr][nc] = true;
                walk(m, nr, nc, dr, dc, steps + 1, seen);
                seen[nr][nc] = false;                       // free it for other routes
            }
        }
    };

    Python

    class Solution:
        def longestRoute(self, mat: list[list[int]], sr: int, sc: int, dr: int, dc: int) -> int:
            if mat[sr][sc] == 0 or mat[dr][dc] == 0:
                return -1
            R, C = len(mat), len(mat[0])
            seen = [[False] * C for _ in range(R)]
            seen[sr][sc] = True
            best = -1
    
            def walk(r: int, c: int, steps: int) -> None:
                nonlocal best
                if r == dr and c == dc:
                    best = max(best, steps)         # reached: keep the longest
                    return
                for a, b in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                    nr, nc = r + a, c + b
                    if 0 <= nr < R and 0 <= nc < C and mat[nr][nc] and not seen[nr][nc]:
                        seen[nr][nc] = True
                        walk(nr, nc, steps + 1)
                        seen[nr][nc] = False        # free it for other routes
    
            walk(sr, sc, 0)
            return best

    Common mistakes

    • Stopping at the first route found, which is not the longest.
    • Forgetting to unmark cells.
    • Counting cells instead of moves (off by one).

    Similar problems