Shortest Distance in a Binary Maze using BFS - Visualization

Visualization Player

Problem Statement

Given an n × m binary matrix grid where each cell can be either 0 or 1, find the shortest path between a source cell and a destination cell. You can only move to a cell with value 1 and you may move only in four directions: up, down, left, and right.

If the path between the source and destination is not possible, return -1.

Note: The source and destination cells must also be 1 to begin with, or the path is impossible.

Examples

Grid Source Destination Shortest Distance Description
[[1,1,0,1],[0,1,1,1],[1,0,0,1],[1,1,1,1]] [0,0] [3,3] 6 Moves: (0,0) → (0,1) → (1,1) → (1,2) → (1,3) → (2,3) → (3,3)
[[1,0,1],[1,1,0],[0,1,1]] [0,0] [2,2] 4 Valid path exists avoiding 0s
[[1,0,0],[0,0,0],[0,0,1]] [0,0] [2,2] -1 No valid path exists
[[1]] [0,0] [0,0] 0 Start and end are the same
[[0]] [0,0] [0,0] -1 Cell is 0; not walkable

Solution

Understanding the Problem

We are given a binary maze represented as a 2D grid, where each cell contains either a 1 (walkable) or a 0 (blocked). Our goal is to find the shortest path from a given source cell to a destination cell by moving only in four directions: up, down, left, or right. The movement is allowed only through cells containing 1.

Think of each cell as a node in an unweighted graph, and the valid movements between walkable cells as edges. To find the shortest number of steps (i.e., the smallest number of edges), the most appropriate strategy is Breadth-First Search (BFS).

Step-by-Step Solution with Example

step 1: Initialize the distance grid

Create a 2D array dist of the same size as the maze, initialized with Infinity to represent that no cell has been visited yet. Set dist[source] to 0 because that’s where we start.

step 2: Initialize the BFS queue

Use a queue to keep track of cells to explore. Each item in the queue contains the current cell’s coordinates and the distance taken to reach it. Initially, enqueue the source cell with distance 0.

step 3: Process the queue

While the queue is not empty, do the following:

  • Dequeue the front cell.
  • Explore its four neighbors (up, down, left, right).
  • For each neighbor, check if:
    • It lies within the bounds of the maze.
    • It is a walkable cell (value 1).
    • It has not been visited via a shorter path before.
  • If all checks pass, update the neighbor’s distance and enqueue it.

step 4: Check for destination

If we reach the destination cell, we immediately return the current distance. This is guaranteed to be the shortest path because BFS explores all possible paths in increasing order of length.

step 5: If queue is exhausted

If the queue becomes empty without reaching the destination, return -1 to indicate that the destination is unreachable.

Example


Input:
maze = [
  [1, 0, 1, 1],
  [1, 1, 1, 0],
  [0, 1, 0, 1],
  [1, 1, 1, 1]
]
source = (0, 0)
destination = (3, 3)

Output: 7

Explanation:
The shortest path is:
(0,0) → (1,0) → (1,1) → (1,2) → (2,1) → (3,1) → (3,2) → (3,3)
which takes 7 steps.

Edge Cases

  • Source or destination is blocked: If either the source or destination cell contains 0, return -1 immediately.
  • Source equals destination: If the source and destination are the same, return 0 because we are already there.
  • Maze with all zeros: The function should handle this by returning -1.
  • Disconnected components: Even if the maze is mostly walkable, ensure that there is a valid path from source to destination.

Finally

Breadth-First Search is ideal for this problem as it finds the shortest path in unweighted graphs like our binary maze. By using a queue and a distance array, we can ensure we explore the most efficient paths first. Always remember to check for edge cases to make your solution robust and reliable.

Algorithm Steps

  1. Check if the source or destination cell is 0. If yes, return -1.
  2. Initialize a 2D array dist with Infinity. Set the distance for the source cell to 0.
  3. Create a queue and add the source cell to it.
  4. While the queue is not empty:
    1. Pop the front cell (x, y) and its distance d.
    2. For each of the four directions (up, down, left, right):
      1. Compute new cell coordinates (nx, ny).
      2. If (nx, ny) is within bounds, has value 1, and not yet visited or has a longer distance:
        • Update dist[nx][ny] = d+1.
        • Enqueue (nx, ny, d+1).
  5. If the destination is reached, return dist[destX][destY].
  6. If the queue is empty and destination was never reached, return -1.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>

#define MAX 100
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};

int min(int a, int b) { return a < b ? a : b; }

int shortestPath(int grid[MAX][MAX], int n, int m, int srcX, int srcY, int destX, int destY) {
    if (grid[srcX][srcY] == 0 || grid[destX][destY] == 0) return -1;
    
    int dist[MAX][MAX];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            dist[i][j] = 1e9;
    
    dist[srcX][srcY] = 0;
    
    int q[MAX * MAX][3], front = 0, rear = 0;
    q[rear][0] = srcX; q[rear][1] = srcY; q[rear][2] = 0; rear++;
    
    while (front < rear) {
        int x = q[front][0], y = q[front][1], d = q[front][2]; front++;
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] == 1 && d + 1 < dist[nx][ny]) {
                dist[nx][ny] = d + 1;
                q[rear][0] = nx; q[rear][1] = ny; q[rear][2] = d + 1; rear++;
            }
        }
    }
    return dist[destX][destY] == 1e9 ? -1 : dist[destX][destY];
}

int main() {
    int grid[3][3] = {{1,1,1},{0,1,0},{1,1,1}};
    int result = shortestPath(grid, 3, 3, 0, 0, 2, 2);
    printf("Shortest Distance: %d\n", result);
    return 0;
}

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...