Find the shortest clear path from top-left to bottom-right using 8-directional BFS
BFS visits vertices in order of increasing distance from the source—a property called "level-order traversal." For unweighted graphs, this guarantees that the first time we reach any vertex, we've found the shortest path. The 8-directional movement treats diagonal steps as having the same cost as orthogonal steps.
BFS is optimal for unweighted shortest paths. For weighted grids, use Dijkstra's algorithm with a priority queue (O(m×n log(m×n))).
The visited array prevents revisiting cells and can store distances for path length queries. The queue holds the BFS frontier—at most all cells in worst case, but typically bounded by the perimeter of the explored region, which is O(√(m×n)) for compact shapes.
Bidirectional BFS from both source and destination can reduce explored cells from O(m×n) to O(√(m×n)) in practice by meeting in the middle.