Shortest Path in Binary Matrix

Medium · Queue & Deque · about 20 minutes

Asked at Meta, Amazon, Google, Microsoft, Mistral AI.

grid is an n × n matrix of 0s and 1s. Travel from the top-left cell to the bottom-right cell using only cells that hold 0, stepping each time to one of the up to 8 surrounding cells (diagonals allowed). Return how many cells the shortest such route passes through, counting both ends, or -1 if no route exists.

Related guides