Search in a Maze

Pattern: Grid graphs

medium

The maze is a grid of open cells '.', walls '#', a start 'S' and an exit 'E'. BFS from S, one step at a time through open cells; the first time E is reached gives the fewest steps.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a grid with exactly one 'S' and one 'E', open cells '.' and walls '#', return the fewest moves (up, down, left, right) from S to E, or -1 if E cannot be reached. The catalogue has no practice link for this one. The guide's own maze task.

Think first

  • What graph is this?
  • Which search gives the fewest steps?
  • What makes a cell passable?

Hints

    Brute force, and why it fails

    DFS over every path and keep the shortest: exponential.

    The key insight

    Every move costs the same, so BFS reaches E first along a shortest route.

    Dry run

    steps0

    Maze S.# / ..# / #.E. Start at (0, 0).

    Step 1 of 3

    The plan

    BFS from S over non-wall cells; return dist[E] when it is reached, else -1
    

    Complexity

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

    Each cell is visited once.

    Edge cases

    • S next to E: 1.
    • E walled off: -1.
    • A long winding corridor.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minSteps(char[][] maze) {
            int R = maze.length, C = maze[0].length;
            int[][] dist = new int[R][C];
            for (int[] row : dist) Arrays.fill(row, -1);
            Queue<int[]> q = new ArrayDeque<>();
            for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (maze[r][c] == 'S') { dist[r][c] = 0; q.add(new int[]{r, c}); }
            int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            while (!q.isEmpty()) {                  // BFS: the first time E is reached is the fewest steps
                int[] cur = q.poll();
                if (maze[cur[0]][cur[1]] == 'E') return dist[cur[0]][cur[1]];
                for (int[] d : dirs) {
                    int r = cur[0] + d[0], c = cur[1] + d[1];
                    if (r >= 0 && c >= 0 && r < R && c < C && maze[r][c] != '#' && dist[r][c] == -1) {
                        dist[r][c] = dist[cur[0]][cur[1]] + 1;
                        q.add(new int[]{r, c});
                    }
                }
            }
            return -1;                              // E cannot be reached
        }
    }

    C++

    class Solution {
    public:
        int minSteps(vector<vector<char>>& maze) {
            int R = static_cast<int>(maze.size()), C = static_cast<int>(maze[0].size());
            vector<vector<int>> dist(R, vector<int>(C, -1));
            queue<pair<int, int>> q;
            for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (maze[r][c] == 'S') { dist[r][c] = 0; q.push(make_pair(r, c)); }
            int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
            while (!q.empty()) {                    // BFS: the first time E is reached is the fewest steps
                pair<int, int> cur = q.front();
                q.pop();
                if (maze[cur.first][cur.second] == 'E') return dist[cur.first][cur.second];
                for (int k = 0; k < 4; k++) {
                    int r = cur.first + dr[k], c = cur.second + dc[k];
                    if (r >= 0 && c >= 0 && r < R && c < C && maze[r][c] != '#' && dist[r][c] == -1) {
                        dist[r][c] = dist[cur.first][cur.second] + 1;
                        q.push(make_pair(r, c));
                    }
                }
            }
            return -1;                              // E cannot be reached
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def minSteps(self, maze: list[list[str]]) -> int:
            R, C = len(maze), len(maze[0])
            start = next((r, c) for r in range(R) for c in range(C) if maze[r][c] == "S")
            dist = {start: 0}
            q = deque([start])
            while q:                                # BFS: the first time E is reached is the fewest steps
                r, c = q.popleft()
                if maze[r][c] == "E":
                    return dist[(r, c)]
                for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= x < R and 0 <= y < C and maze[x][y] != "#" and (x, y) not in dist:
                        dist[(x, y)] = dist[(r, c)] + 1
                        q.append((x, y))
            return -1                               # E cannot be reached

    Common mistakes

    • Using DFS for the shortest route.
    • Treating E as a wall.

    Similar problems