VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-path-in-a-binary-maze/

⇱ Shortest Path in a Binary Maze - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest Path in a Binary Maze

Last Updated : 13 Jun, 2026

Given a binary matrix mat[][] of size n × m containing values 0 and 1, and a source cell src[] and destination cell dest[], find the minimum number of steps required to reach the destination cell from the source cell. From any cell, you can move to its adjacent cells in the up, down, left, and right directions.

  • 1 represents a traversable cell.
  • 0 represents a blocked cell that cannot be visited.

If the destination cannot be reached from the source, return -1.

Example:

Input: mat[][] = {{1, 1, 1, 1},{1, 1, 0, 1},{1, 1, 1, 1},{1, 1, 0, 0},{1, 0, 0, 1}}, src[] = {0, 1}, dest[] = {2, 2}
Output: 3
Explanation: From (0,1), the minimum number of steps to reach (2,2) is 3,

👁 qq

Input: mat[][] = {{1, 1, 1, 1, 1},{1, 1, 1, 1, 1},{1, 1, 1, 1, 0},{1, 0, 1, 0, 1}}, src[] = {0, 0}, dest[] = {3, 4}
Output:-1
Explanation: From (0,0), the destination (3,4) cannot be reached because all possible paths are blocked by 0 cells, so no valid route exists.

👁 ww

[Naive Approach] Using DFS - O(4^n*m) Time and O(m × n) Space

The idea is to start from the source cell and recursively explore all possible paths to reach the destination cell in the binary matrix. From any cell, we can move in four possible directions: up, down, left, and right, as long as the next cell is valid (inside the grid, not blocked, and not already visited in the current path).

We maintain a visited matrix to avoid cycles and ensure we do not revisit the same cell in a single path. A global variable minDist is used to store the minimum distance found across all possible paths.

Base Cases:

  • If the current cell (x, y) is equal to the destination cell (dx, dy), we update minDist with the minimum of the current distance and return.
  • If the current cell is out of bounds or blocked or already visited, we stop exploring that path.

The recurrence relation will be: dfs(x, y) = dfs(x+1, y) + dfs(x-1, y) + dfs(x, y+1) + dfs(x, y-1)


Output
3

[Expected Approach] Using BFS - O(n × m) Time and O(n× m) Space

The idea is to use Breadth First Search (BFS) to find the shortest path in the binary matrix. We start from the source cell and explore all reachable cells level by level using a queue.

Each queue element stores the cell coordinates along with the distance from the source. Since BFS explores all nodes at the current distance before moving to the next level, the first time we reach the destination cell, it gives the minimum number of steps.

We mark cells as visited (set them to 0) to avoid revisiting and ensure each cell is processed only once.

Base Cases:

  • If the source or destination cell is blocked (0), return -1.
  • If the destination is reached during BFS traversal, return the current distance.

Output
3
Comment