Shortest Path in Binary Maze


Shortest Path in a Binary Maze


Problem Statement

You are given an n × m grid where each cell contains either:

You must find the shortest path length (minimum number of steps) from a given source cell to a destination cell. Moves are allowed in four directions: up, down, left, right. Return -1 if the destination is not reachable.


This problem is best solved using multi-source BFS on the grid:

This method is also known as the Lee algorithm in grid/maze pathfinding.


Algorithm Steps

  1. Check inputs:

    • If grid[src.x][src.y] == 0 or grid[dest.x][dest.y] == 0, return -1 immediately.
  2. Initialize:

    • A 2D boolean visited array, same size as the grid, all initially false.

    • A BFS queue storing QueueNode { x, y, dist }.

  3. Enqueue Source:

    • Mark source visited, push (src.x, src.y, 0) into queue.
  4. BFS Loop:

    • While the queue is not empty:

      • Pop front node (x, y, dist).

      • If this equals destination, return dist.

      • Otherwise, for each of four neighbor positions (nx, ny):

        • If in grid bounds, cell value is 1, and not visited:

          • Mark visited and enqueue (nx, ny, dist + 1).
  5. If BFS completes without hitting destination, return -1.


Java Code (Grid BFS / Lee Algorithm)

class Solution {
    static class Node {
        int x, y, dist;
        Node(int x, int y, int dist) {
            this.x = x; this.y = y; this.dist = dist;
        }
    }

    public int shortestPath(int[][] grid, int sx, int sy, int dx, int dy) {
        int n = grid.length, m = grid[0].length;
        if (grid[sx][sy] == 0 || grid[dx][dy] == 0) return -1;

        boolean[][] visited = new boolean[n][m];
        Queue<Node> q = new LinkedList<>();
        int[] dx4 = {-1, 0, 0, 1};
        int[] dy4 = {0, -1, 1, 0};

        visited[sx][sy] = true;
        q.add(new Node(sx, sy, 0));

        while (!q.isEmpty()) {
            Node curr = q.poll();
            int x = curr.x, y = curr.y, dist = curr.dist;
            if (x == dx && y == dy) return dist;
            for (int i = 0; i < 4; i++) {
                int nx = x + dx4[i], ny = y + dy4[i];
                if (nx >= 0 && ny >= 0 && nx < n && ny < m
                        && grid[nx][ny] == 1 && !visited[nx][ny]) {
                    visited[nx][ny] = true;
                    q.add(new Node(nx, ny, dist + 1));
                }
            }
        }
        return -1;
    }
}

Dry Run Example

Grid:

1 0 1 1 1
1 1 0 1 1
0 1 1 1 0

Source (0,0), Destination (2,2):


Time and Space Complexity

Metric Complexity
Time O(n × m)
Space O(n × m) for visited and queue

Why BFS Works—Key Points


Comparison with Other Approaches


When to Use This Template