Shortest Distance in a Binary Maze using BFS
Problem and examples
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.
| 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 |
Explore Shortest Distance in a Binary Maze using BFS
Load an example or enter your own input. Use the player controls to follow each change.
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-1immediately. - Source equals destination: If the source and destination are the same, return
0because 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.
- Check if the source or destination cell is
0. If yes, return-1. - Initialize a 2D array
distwithInfinity. Set the distance for the source cell to0. - Create a queue and add the source cell to it.
- While the queue is not empty:
- Pop the front cell
(x, y)and its distanced. - For each of the four directions (up, down, left, right):
- Compute new cell coordinates
(nx, ny). - If
(nx, ny)is within bounds, has value1, and not yet visited or has a longer distance: - Update
dist[nx][ny]=d+1. - Enqueue
(nx, ny, d+1). - If the destination is reached, return
dist[destX][destY]. - If the queue is empty and destination was never reached, return
-1.
Implementation and efficiency
C implementation
#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;
}C++ implementation
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int shortestPath(vector<vector<int>>& grid, pair<int,int> src, pair<int,int> dest) {
int n = grid.size(), m = grid[0].size();
if (grid[src.first][src.second] == 0 || grid[dest.first][dest.second] == 0) return -1;
vector<vector<int>> dist(n, vector<int>(m, 1e9));
dist[src.first][src.second] = 0;
queue<tuple<int,int,int>> q;
q.push({src.first, src.second, 0});
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
while (!q.empty()) {
auto [x, y, d] = q.front(); q.pop();
for (auto& dir : dirs) {
int nx = x + dir[0], ny = y + dir[1];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] == 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1;
q.push({nx, ny, d + 1});
}
}
}
return dist[dest.first][dest.second] == 1e9 ? -1 : dist[dest.first][dest.second];
}
int main() {
vector<vector<int>> grid = {{1,1,1},{0,1,0},{1,1,1}};
cout << "Shortest Distance: " << shortestPath(grid, {0,0}, {2,2}) << endl;
return 0;
}Python implementation
from collections import deque
def shortest_path(grid, source, destination):
n, m = len(grid), len(grid[0])
sx, sy = source
dx, dy = destination
if grid[sx][sy] == 0 or grid[dx][dy] == 0:
return -1
directions = [(0,1), (1,0), (0,-1), (-1,0)]
dist = [[float('inf')] * m for _ in range(n)]
dist[sx][sy] = 0
q = deque([(sx, sy, 0)])
while q:
x, y, d = q.popleft()
for dx_, dy_ in directions:
nx, ny = x + dx_, y + dy_
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == 1 and d + 1 < dist[nx][ny]:
dist[nx][ny] = d + 1
q.append((nx, ny, d + 1))
return -1 if dist[dx][dy] == float('inf') else dist[dx][dy]
grid = [[1,1,1],[0,1,0],[1,1,1]]
print("Shortest Distance:", shortest_path(grid, (0,0), (2,2)))Java implementation
import java.util.*;
public class ShortestPathBinaryMaze {
static int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
public static int shortestPath(int[][] grid, int[] source, int[] dest) {
int n = grid.length, m = grid[0].length;
if (grid[source[0]][source[1]] == 0 || grid[dest[0]][dest[1]] == 0) return -1;
int[][] dist = new int[n][m];
for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
dist[source[0]][source[1]] = 0;
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{source[0], source[1], 0});
while (!q.isEmpty()) {
int[] curr = q.poll();
int x = curr[0], y = curr[1], d = curr[2];
for (int[] dir : directions) {
int nx = x + dir[0], ny = y + dir[1];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] == 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1;
q.offer(new int[]{nx, ny, d + 1});
}
}
}
return dist[dest[0]][dest[1]] == Integer.MAX_VALUE ? -1 : dist[dest[0]][dest[1]];
}
public static void main(String[] args) {
int[][] grid = {{1,1,1},{0,1,0},{1,1,1}};
int result = shortestPath(grid, new int[]{0,0}, new int[]{2,2});
System.out.println("Shortest Distance: " + result);
}
}JavaScript implementation
function shortestPathBinaryMaze(grid, source, destination) {
const [n, m] = [grid.length, grid[0].length];
const [srcX, srcY] = source;
const [destX, destY] = destination;
if (grid[srcX][srcY] === 0 || grid[destX][destY] === 0) return -1;
const directions = [[0,1],[1,0],[0,-1],[-1,0]];
const dist = Array.from({ length: n }, () => Array(m).fill(Infinity));
dist[srcX][srcY] = 0;
const queue = [[srcX, srcY, 0]];
while (queue.length > 0) {
const [x, y, d] = queue.shift();
for (const [dx, dy] of directions) {
const [nx, ny] = [x + dx, y + dy];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] === 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1;
queue.push([nx, ny, d + 1]);
}
}
}
return dist[destX][destY] === Infinity ? -1 : dist[destX][destY];
}
const grid = [[1,1,1],[0,1,0],[1,1,1]];
console.log("Shortest Distance:", shortestPathBinaryMaze(grid, [0,0], [2,2]));Go implementation
package main
import (
"container/list"
"fmt"
)
func shortestPath(grid [][]int, srcX, srcY, destX, destY int) int {
n, m := len(grid), len(grid[0])
if grid[srcX][srcY] == 0 || grid[destX][destY] == 0 {
return -1
}
dist := make([][]int, n)
for i := range dist {
dist[i] = make([]int, m)
for j := range dist[i] {
dist[i][j] = 1e9
}
}
dist[srcX][srcY] = 0
q := list.New()
q.PushBack([3]int{srcX, srcY, 0})
dirs := [][2]int{{0,1},{1,0},{0,-1},{-1,0}}
for q.Len() > 0 {
e := q.Remove(q.Front()).([3]int)
x, y, d := e[0], e[1], e[2]
for _, dir := range dirs {
nx, ny := x + dir[0], y + dir[1]
if nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] == 1 && d+1 < dist[nx][ny] {
dist[nx][ny] = d + 1
q.PushBack([3]int{nx, ny, d + 1})
}
}
}
if dist[destX][destY] == 1e9 {
return -1
}
return dist[destX][destY]
}
func main() {
grid := [][]int{{1,1,1},{0,1,0},{1,1,1}}
fmt.Println("Shortest Distance:", shortestPath(grid, 0, 0, 2, 2))
}Rust implementation
use std::collections::VecDeque;
fn shortest_path(grid: Vec<Vec<i32>>, src: (usize, usize), dest: (usize, usize)) -> i32 {
let (n, m) = (grid.len(), grid[0].len());
if grid[src.0][src.1] == 0 || grid[dest.0][dest.1] == 0 {
return -1;
}
let mut dist = vec![vec![i32::MAX; m]; n];
dist[src.0][src.1] = 0;
let mut queue = VecDeque::new();
queue.push_back((src.0, src.1, 0));
let dirs = [(0,1),(1,0),(0,-1),(-1,0)];
while let Some((x, y, d)) = queue.pop_front() {
for (dx, dy) in &dirs {
let (nx, ny) = (x as isize + dx, y as isize + dy);
if nx >= 0 && ny >= 0 && (nx as usize) < n && (ny as usize) < m &&
grid[nx as usize][ny as usize] == 1 && d + 1 < dist[nx as usize][ny as usize] {
dist[nx as usize][ny as usize] = d + 1;
queue.push_back((nx as usize, ny as usize, d + 1));
}
}
}
if dist[dest.0][dest.1] == i32::MAX { -1 } else { dist[dest.0][dest.1] }
}
fn main() {
let grid = vec![vec![1,1,1],vec![0,1,0],vec![1,1,1]];
let res = shortest_path(grid, (0,0), (2,2));
println!("Shortest Distance: {}", res);
}Kotlin implementation
fun shortestPath(grid: Array<IntArray>, source: Pair<Int, Int>, dest: Pair<Int, Int>): Int {
val n = grid.size
val m = grid[0].size
if (grid[source.first][source.second] == 0 || grid[dest.first][dest.second] == 0) return -1
val dist = Array(n) { IntArray(m) { Int.MAX_VALUE } }
val queue = ArrayDeque<Triple<Int, Int, Int>>()
dist[source.first][source.second] = 0
queue.add(Triple(source.first, source.second, 0))
val dirs = arrayOf(Pair(0,1), Pair(1,0), Pair(0,-1), Pair(-1,0))
while (queue.isNotEmpty()) {
val (x, y, d) = queue.removeFirst()
for ((dx, dy) in dirs) {
val nx = x + dx
val ny = y + dy
if (nx in 0 until n && ny in 0 until m && grid[nx][ny] == 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1
queue.add(Triple(nx, ny, d + 1))
}
}
}
return if (dist[dest.first][dest.second] == Int.MAX_VALUE) -1 else dist[dest.first][dest.second]
}
fun main() {
val grid = arrayOf(
intArrayOf(1,1,1),
intArrayOf(0,1,0),
intArrayOf(1,1,1)
)
println("Shortest Distance: ${shortestPath(grid, 0 to 0, 2 to 2)}")
}Swift implementation
import Foundation
func shortestPath(_ grid: [[Int]], _ source: (Int, Int), _ dest: (Int, Int)) -> Int {
let n = grid.count, m = grid[0].count
if grid[source.0][source.1] == 0 || grid[dest.0][dest.1] == 0 {
return -1
}
var dist = Array(repeating: Array(repeating: Int.max, count: m), count: n)
var queue: [(Int, Int, Int)] = [(source.0, source.1, 0)]
dist[source.0][source.1] = 0
let dirs = [(0,1),(1,0),(0,-1),(-1,0)]
while !queue.isEmpty {
let (x, y, d) = queue.removeFirst()
for (dx, dy) in dirs {
let nx = x + dx, ny = y + dy
if nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] == 1 && d + 1 < dist[nx][ny] {
dist[nx][ny] = d + 1
queue.append((nx, ny, d + 1))
}
}
}
return dist[dest.0][dest.1] == Int.max ? -1 : dist[dest.0][dest.1]
}
let grid = [[1,1,1],[0,1,0],[1,1,1]]
print("Shortest Distance:", shortestPath(grid, (0,0), (2,2)))TypeScript implementation
function shortestPath(grid: number[][], source: [number, number], destination: [number, number]): number {
const [n, m] = [grid.length, grid[0].length];
const [sx, sy] = source, [dx, dy] = destination;
if (grid[sx][sy] === 0 || grid[dx][dy] === 0) return -1;
const dist: number[][] = Array.from({ length: n }, () => Array(m).fill(Infinity));
dist[sx][sy] = 0;
const queue: [number, number, number][] = [[sx, sy, 0]];
const directions = [[0,1],[1,0],[0,-1],[-1,0]];
while (queue.length) {
const [x, y, d] = queue.shift()!;
for (const [dx_, dy_] of directions) {
const [nx, ny] = [x + dx_, y + dy_];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] === 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1;
queue.push([nx, ny, d + 1]);
}
}
}
return dist[dx][dy] === Infinity ? -1 : dist[dx][dy];
}
const grid = [[1,1,1],[0,1,0],[1,1,1]];
console.log("Shortest Distance:", shortestPath(grid, [0,0], [2,2]));