oneby7

Graphs Fewest steps with BFS

445. Shortest Path in Binary Matrix

Medium

You are given a square grid of integers, grid, with n rows and n columns. A cell that holds 0 is open, and a cell that holds 1 is blocked.

A clear path starts at the top-left cell, (0, 0), and ends at the bottom-right cell, (n - 1, n - 1). It visits only open cells. Each step moves to one of the eight cells around the current one: up, down, left, right, or one of the four diagonals. The length of a path is the number of cells it visits, counting the first and the last.

Return the length of the shortest clear path. If there is no clear path, return -1.

Example 1

000101101110001100011001000000110100

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

Output: 9

Explanation: The blocked cells in the middle push the path down the left side. One shortest path visits (0, 0), (1, 1), (2, 1), (3, 0), (4, 1), (4, 2), (4, 3), (4, 4) and (5, 5), which is 9 cells.

Example 2

010110000

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

Output: -1

Explanation: All three cells around the top-left cell are blocked, so no path can leave it.

Example 3

0

Input: grid = [[0]]

Output: 1

Explanation: The top-left cell is also the bottom-right cell. The path is that one cell, so its length is 1.

Check your understanding

Work out the answer for this input before you write any code.

grid = [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 300
  • grid[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.