Shortest Path in Binary Matrix

Medium · Graphs · Array · Breadth-First Search · Matrix

Problem

You are given an n x n grid of 0s and 1s. A clear path goes from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1) so that:

The length of a clear path is the number of cells it visits, both ends included. Return the length of the shortest clear path, or -1 if there is none.

Examples

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

(0,0) -> (0,1) -> (1,2) -> (2,2): a diagonal step from (0,1) to (1,2) gives 4 cells.

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

The bottom-right cell is 1, so no path can end there.

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

The start is already the end: a path of one cell.

Constraints

Approaches

Follow-up

BFS works because every step has the same cost. If a diagonal step cost more than a straight one (say 1.4 instead of 1), the fewest steps would no longer be the shortest path; you would switch to Dijkstra's algorithm, or A* with the straight-line distance to the corner as the guide.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…