#1091

Shortest Path in Binary Matrix

specialist · 850 · lc medium +31 · verified · 51.2% accepted · 7,391 likes · top 40%

Description

Given an n x n binary grid, find the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1). A clear path visits only 0-valued cells and may move in all 8 directions. Path length is the number of cells visited.

Return the length of the shortest clear path, or -1 if none exists.

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

Code

1
2
3