Shortest Path in Binary Matrix

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

You're given a grid of tiles. Each tile is either open (0) or blocked (1). From an open tile, you can step to any of its 8 neighbors if that neighbor is open. That includes the 4 diagonal neighbors.

Return the length of the shortest path from the top-left tile to the bottom-right tile. Count the tiles on the path, including both ends. If there's no path, return -1.

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

Output: 3

Go diagonally through the center tile. That connects the top-left and bottom-right corners in just 3 tiles.

Input: grid = [[1]]

Output: -1

The only tile is blocked. So the path can't even start.

Input: grid = [[0]]

Output: 1

The start and the end are the same open tile. So the path length is 1.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

How many tiles long is the shortest path from the top-left to the bottom-right of this grid? Diagonal moves are allowed. grid = [[0, 0, 1], [1, 0, 1], [1, 0, 0]]
3
5
-1
2

Remember to understand the problem and plan your approach before you start coding.