Classic BFS, and I knew it was BFS the moment I read it.
Model the matrix as an unweighted graph where each 0-cell is a node and edges connect to its 8 neighbors. Use BFS from the top-left cell to find the shortest path to the bottom-right cell, tracking distance and returning -1 if unreachable.
Pro tip: Mention that BFS is optimal for unweighted graphs and that using a deque with level-order traversal avoids storing distances separately. Also, note that early termination when reaching the target can save time.
Confirm the matrix is n x n, binary, and that start and end cells are 0. Handle edge cases like n=1 or blocked start/end.
Use BFS because all edges have equal weight. Each state is a cell (row, col) and distance from start.
Initialize a queue with the start cell and a visited set. For each cell, explore all 8 neighbors that are within bounds, have value 0, and are unvisited.
Increment distance per BFS level. If the target cell is dequeued, return the distance. If the queue empties, return -1.
Time and space are O(n^2). Optionally, modify the matrix in-place to mark visited cells, saving space.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.