Find shortest safe route in a path with landmines

Pattern: Rat in a maze

medium

First mark every landmine and its four neighbours as unsafe. Then run a breadth-first search from every safe cell in the first column at once. The first time it reaches the last column, the number of moves is the shortest safe route.

The problem

A rectangular field has safe cells (1) and landmines (0). A landmine also makes its four neighbours (up, down, left, right) unsafe. Starting from any safe cell in the first column and moving up, down, left or right through safe cells only, return the fewest moves needed to reach any cell in the last column, or -1 if it cannot be done. For example, the 12 × 10 field in the GeeksforGeeks article gives 13.

The link above is a GeeksforGeeks article. The function name shortestSafeRoute and the rule "count moves, -1 if impossible" are this guide's own.

Think first

  • Which cells are really usable once the landmines' neighbours are removed?
  • Why is breadth-first search right for "fewest moves"?
  • How do you start from many cells at once?

Hints

    Brute force, and why it fails

    Backtracking over every path from every start, keeping the shortest, is exponential. Breadth-first search visits each cell once: O(R × C).

    The key insight

    "Fewest steps" in a grid where every step costs the same is a breadth-first search question. Starting all the left cells together answers "from any of them" in one pass.

    Dry run

    1 0 10 
    1 1 11 
    1 1 12 

    The grid is 1 0 1, 1 1 1, 1 1 1. The landmine at (0, 1) makes (0, 0), (0, 2) and (1, 1) unsafe as well.

    Step 1 of 4

    The plan

    safe = cells that are 1 and not next to a 0
    dist = all -1; queue = every safe cell in column 0, with dist 0
    while queue is not empty:
        (r, c) = pop front
        if c == last column: return dist[r][c]
        for each safe neighbour with dist -1: dist = dist[r][c] + 1; push it
    return -1
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    Marking unsafe cells and the search each touch every cell a constant number of times.

    Edge cases

    • One column: any safe cell is already on the last column, so 0.
    • A landmine in the first column: it and its neighbours cannot be starts.
    • No safe route: -1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int shortestSafeRoute(int[][] mat) {
            int R = mat.length, C = mat[0].length;
            boolean[][] safe = new boolean[R][C];
            int[] dr = {1, -1, 0, 0}, dc = {0, 0, 1, -1};
            for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) safe[r][c] = mat[r][c] == 1;
            for (int r = 0; r < R; r++)                     // a landmine also makes its four neighbours unsafe
                for (int c = 0; c < C; c++)
                    if (mat[r][c] == 0)
                        for (int k = 0; k < 4; k++) {
                            int nr = r + dr[k], nc = c + dc[k];
                            if (nr >= 0 && nc >= 0 && nr < R && nc < C) safe[nr][nc] = false;
                        }
            int[][] dist = new int[R][C];
            for (int[] row : dist) Arrays.fill(row, -1);
            Deque<int[]> queue = new ArrayDeque<>();
            for (int r = 0; r < R; r++) if (safe[r][0]) { dist[r][0] = 0; queue.add(new int[]{r, 0}); }   // start anywhere on the left
            while (!queue.isEmpty()) {                      // breadth-first: the first time we reach the right is the shortest
                int[] cur = queue.poll();
                if (cur[1] == C - 1) return dist[cur[0]][cur[1]];
                for (int k = 0; k < 4; k++) {
                    int nr = cur[0] + dr[k], nc = cur[1] + dc[k];
                    if (nr < 0 || nc < 0 || nr >= R || nc >= C || !safe[nr][nc] || dist[nr][nc] != -1) continue;
                    dist[nr][nc] = dist[cur[0]][cur[1]] + 1;
                    queue.add(new int[]{nr, nc});
                }
            }
            return -1;
        }
    }

    C++

    class Solution {
    public:
        int shortestSafeRoute(vector<vector<int>>& mat) {
            int R = static_cast<int>(mat.size()), C = static_cast<int>(mat[0].size());
            const int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
            vector<vector<bool>> safe(R, vector<bool>(C));
            for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) safe[r][c] = mat[r][c] == 1;
            for (int r = 0; r < R; r++)                     // a landmine also makes its four neighbours unsafe
                for (int c = 0; c < C; c++)
                    if (mat[r][c] == 0)
                        for (int k = 0; k < 4; k++) {
                            int nr = r + dr[k], nc = c + dc[k];
                            if (nr >= 0 && nc >= 0 && nr < R && nc < C) safe[nr][nc] = false;
                        }
            vector<vector<int>> dist(R, vector<int>(C, -1));
            queue<pair<int, int>> q;
            for (int r = 0; r < R; r++) if (safe[r][0]) { dist[r][0] = 0; q.push(make_pair(r, 0)); }   // start on the left
            while (!q.empty()) {                            // breadth-first: the first time we reach the right is the shortest
                pair<int, int> cur = q.front();
                q.pop();
                if (cur.second == C - 1) return dist[cur.first][cur.second];
                for (int k = 0; k < 4; k++) {
                    int nr = cur.first + dr[k], nc = cur.second + dc[k];
                    if (nr < 0 || nc < 0 || nr >= R || nc >= C || !safe[nr][nc] || dist[nr][nc] != -1) continue;
                    dist[nr][nc] = dist[cur.first][cur.second] + 1;
                    q.push(make_pair(nr, nc));
                }
            }
            return -1;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def shortestSafeRoute(self, mat: list[list[int]]) -> int:
            R, C = len(mat), len(mat[0])
            steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
            safe = [[mat[r][c] == 1 for c in range(C)] for r in range(R)]
            for r in range(R):                      # a landmine also makes its four neighbours unsafe
                for c in range(C):
                    if mat[r][c] == 0:
                        for dr, dc in steps:
                            if 0 <= r + dr < R and 0 <= c + dc < C:
                                safe[r + dr][c + dc] = False
            dist = [[-1] * C for _ in range(R)]
            q = deque()
            for r in range(R):                      # start anywhere on the left
                if safe[r][0]:
                    dist[r][0] = 0
                    q.append((r, 0))
            while q:                                # breadth-first: the first time we reach the right is the shortest
                r, c = q.popleft()
                if c == C - 1:
                    return dist[r][c]
                for dr, dc in steps:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < R and 0 <= nc < C and safe[nr][nc] and dist[nr][nc] == -1:
                        dist[nr][nc] = dist[r][c] + 1
                        q.append((nr, nc))
            return -1

    Common mistakes

    • Forgetting that neighbours of landmines are unsafe too.
    • Marking unsafe cells while reading the grid in the same pass, which spreads the danger further than it should.
    • Using depth-first search, which finds a route but not the shortest.

    Similar problems