Shortest Path in Binary Matrix
MediumThis 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
Remember to understand the problem and plan your approach before you start coding.