Skip to main content

Shortest Path in Binary Matrix - Solution & Explanation

MediumArrayBreadth-First SearchMatrix13 min readAsked at: Amazon, Microsoft, Apple +12
Practice this problem

Problem Statement

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

  • All the visited cells of the path are 0.
  • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).

The length of a clear path is the number of visited cells of this path.

 

Example 1:

Input: grid = [[0,1],[1,0]]
Output: 2

Example 2:

Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

Example 3:

Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1

 

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1

Approach Overview

Problem Overview: Given an n x n binary grid, find the length of the shortest path from the top-left cell to the bottom-right cell. Cells with value 0 are open and 1 are blocked. Movement is allowed in 8 directions (horizontal, vertical, and diagonal). If no path exists, return -1.

Approach 1: Breadth-First Search (BFS) Traversal (Time: O(n²), Space: O(n²))

Treat the grid as an implicit graph where each cell is a node and edges connect the 8 neighboring cells. Start a Breadth-First Search from (0,0) if the cell is open. BFS explores the grid level by level, which naturally finds the shortest path in an unweighted graph. Use a queue to process cells and mark visited cells directly in the grid or with a visited matrix to avoid revisiting. For every cell removed from the queue, iterate through the 8 possible directions and enqueue valid neighbors with distance +1. Because each cell is processed at most once, the traversal runs in O(n²) time with O(n²) space for the queue and visited tracking.

This approach works well because all edges have equal cost. BFS guarantees the first time you reach the bottom-right cell is the shortest path length. The grid structure also keeps the implementation simple since neighbors can be generated using a fixed direction array.

Approach 2: A* Search Algorithm (Time: O(n² log n), Space: O(n²))

The A* algorithm improves practical performance by guiding the search toward the target using a heuristic. Instead of a simple queue, maintain a priority queue ordered by f(n) = g(n) + h(n), where g(n) is the distance from the start and h(n) is a heuristic estimate to the goal. For this problem, the Chebyshev distance works well because diagonal movement is allowed. Each step expands the node with the smallest estimated total distance. In dense grids or large search spaces, A* often explores fewer cells than BFS.

The implementation still iterates over the 8 neighbors for every expanded node and updates distances when a shorter path is found. While the worst-case complexity remains O(n² log n) due to heap operations, the heuristic significantly reduces unnecessary exploration in many cases.

Recommended for interviews: BFS is the expected solution. Interviewers want to see that you recognize the grid as an unweighted graph and immediately apply BFS. Mentioning that the grid can be modeled as a graph and exploring neighbors in 8 directions demonstrates strong fundamentals in matrix traversal and array-based graph problems. A* is a strong follow-up discussion if optimization or pathfinding algorithms come up.

Approach 1: Breadth-First Search Approach

This approach involves using BFS to find the shortest path in an unweighted graph. BFS is well-suited for finding the shortest path because it explores all nodes at the present depth prior to moving on to nodes at the next depth level. By maintaining a queue that stores the current cell position and path length, we can efficiently determine the shortest path to the destination. Moreover, since the path can proceed in 8 possible directions, we must consider all potential moves from a given cell.

The function shortestPathBinaryMatrix uses BFS to explore each adjacent cell of the current cell in all 8 possible directions. The grid has been marked to indicate which cells have been visited, avoiding revisiting them and ensuring efficient path finding. If the bottom-right corner is reached, the function returns the path length; otherwise, it returns -1 if no path exists.

Code

Python

C++

Java

Complexity

Time Complexity: O(n^2) because in the worst case, each cell of the n x n grid is visited once.
Space Complexity: O(n^2) due to the space needed to store the BFS queue.

Try this approach in the editor →

Approach 2: A* Search Algorithm Approach

A* is a popular pathfinding and graph traversal algorithm. It is capable of focusing specifically on the shortest path with the use of heuristics. In this case, the heuristic is the Chebyshev distance between the current cell and the bottom-right corner, which matches the grid's 8-directional movement. By combining the BFS strategy with a heuristic score, A* ensures an efficient pathfinding solution while avoiding unnecessary paths.

This solution deploys the A* algorithm to find the shortest clear path by including a heuristic function, ensuring efficient traversal through the grid by prioritizing paths closer to the end point.

Code

Python

C++

Complexity

Time Complexity: O(n^2 * log(n)) because each cell is processed once with priority queue operations.
Space Complexity: O(n^2) for the priority queue and grid storage.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Breadth-First Search Approach

Time Complexity: O(n^2) because in the worst case, each cell of the n x n grid is visited once.
Space Complexity: O(n^2) due to the space needed to store the BFS queue.

A* Search Algorithm Approach

Time Complexity: O(n^2 * log(n)) because each cell is processed once with priority queue operations.
Space Complexity: O(n^2) for the priority queue and grid storage.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Breadth-First Search (BFS)O(n²)O(n²)Best general solution for shortest path in an unweighted grid
A* Search AlgorithmO(n² log n)O(n²)When heuristic guidance can reduce explored nodes in large grids

Video Solution

Shortest Path in a Binary Matrix - Leetcode 1091 - PythonNeetCodeIO49,609 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Shortest Path in Binary Matrix easy or hard?
Shortest Path in Binary Matrix is classified as a Medium problem. The difficulty comes from recognizing that the grid represents an unweighted graph and that BFS guarantees the shortest path. Once that pattern is clear, the implementation becomes straightforward.
Shortest Path in Binary Matrix Python/Java solution
Most implementations use BFS with a queue and a list of 8 direction vectors. Python solutions typically use collections.deque for efficient queue operations, while Java solutions use Queue or ArrayDeque. Both versions iterate through neighbors and return the path length when the bottom-right cell is reached.
How to solve Shortest Path in Binary Matrix in O(n²)?
Use Breadth-First Search starting from cell (0,0). Push the starting cell into a queue, then repeatedly pop cells and explore their 8 neighboring positions if they contain 0 and have not been visited. Track the path length while expanding levels. Since each cell is visited once, the total work stays within O(n²).
What is the best approach for Shortest Path in Binary Matrix?
Breadth-First Search (BFS) is the best approach because the grid forms an unweighted graph and BFS always finds the shortest path in such graphs. Starting from the top-left cell, BFS explores neighbors level by level until the bottom-right cell is reached. The algorithm runs in O(n²) time and O(n²) space for an n x n grid.
Is Shortest Path in Binary Matrix asked at Google/Amazon/Meta?
Shortest Path in Binary Matrix is a common interview problem for companies that test graph traversal and grid search patterns. Variants of this problem appear in interviews at companies like Amazon, Google, and Meta because it evaluates BFS fundamentals and matrix traversal logic.
What data structure is used in Shortest Path in Binary Matrix?
The primary data structure is a queue used for Breadth-First Search. The queue stores grid coordinates along with the current path length. Some implementations also use a visited matrix or modify the input grid to mark visited cells.
What is the time complexity of Shortest Path in Binary Matrix?
The optimal BFS solution runs in O(n²) time because each cell in the n x n grid is processed at most once. For every cell, the algorithm checks up to 8 neighbors. The space complexity is also O(n²) due to the queue and visited tracking.

Ready to solve this problem?

Practice Shortest Path in Binary Matrix with our built-in code editor and test cases.

Practice on FleetCode