Problem 172
Shortest Path in Binary Matrix
Medium · 20 pts · Matrix, Breadth-First Search
Problem
You are given an N x N grid where '0' is an open cell and '1' is blocked. Find the length of the shortest clear path from the top-left cell to the bottom-right cell. You may move to any of the 8 neighbouring cells, including diagonals, but only through open cells. The length counts the cells on the path, including the first and the last. If either corner is blocked or no path exists, print -1. Breadth-first search from the top-left cell over the 8 directions gives the shortest path.
Input
First line: integer N. Next N lines: N characters, each '0' or '1'.
Output
Print the path length, or -1.
Constraints
1 <= N <= 100
Example input
2 01 10
Example output
2
Explanation
In the 2 x 2 grid 01 / 10, the top-left and bottom-right cells are open and the other two are blocked. One diagonal move connects them, so the path has 2 cells.