Shortest Path in Binary Matrix
Find the shortest 8-directionally connected path of 0-cells from top-left to bottom-right.
Open on LeetCode ↗Intuition
Two traps sink most first attempts. The first is using only 4 directions out of habit; this problem explicitly allows diagonal moves, so a 4-direction BFS can report a path longer than the true shortest, or miss one entirely. The second is marking a cell visited when it is dequeued instead of when it is enqueued; if you wait until dequeue, the same cell can be pushed onto the queue many times before it is ever processed, and the run time degrades badly. Mark on enqueue, expand in all 8 directions, and standard BFS distance-by-layer logic gives the answer.
Approach
Guard the endpoints
If the start or end cell is itself blocked (1), no path exists at all, so return -1 immediately without starting BFS.
8-directional BFS, mark on enqueue
Push (0,0) with path length 1 and mark it visited right away. For each popped cell, check all 8 neighbors; any open, unvisited neighbor is marked visited the instant it is pushed, not when it is later popped.
Stop at the target
The first time the bottom-right cell is popped, its stored path length is the shortest possible, because BFS explores in nondecreasing distance order.
Solution & live demo
Edge cases
Return -1 before any traversal.
Start equals end; answer is 1.
Queue empties without reaching the target; return -1.
8-directional expansion finds it; a 4-direction BFS would overcount.