Problem Description
Given an n x n binary matrix, find the length of the shortest clear path from the top-left cell to the bottom-right cell. A clear path only visits cells with 0 and allows moves in 8 directions (horizontal, vertical, and diagonal connections). If either the start or end cell is blocked or no such path exists, return -1.
Key Insights
- Use Breadth-First Search (BFS) to guarantee the shortest path in an unweighted grid.
- Movement is allowed in 8 directions, so each cell has up to 8 neighbors.
- Check boundary conditions and ensure only unvisited cells with value 0 are processed.
- Mark cells as visited to avoid reprocessing and infinite loops.
- If the start or finish is blocked (==1), the answer is immediately -1.
Space and Time Complexity
Time Complexity: O(n^2), as in the worst-case scenario every cell in the grid is visited once. Space Complexity: O(n^2), due to the queue used for BFS and storage for visited cells.
Solution
We approach this problem using BFS, which is ideal for finding the shortest path in a grid when each move has the same cost. Initialize the BFS from the top-left cell if it is 0. For every cell dequeued, explore its 8 neighboring cells. If a neighboring cell is within grid bounds, has a value of 0, and hasn’t been visited, mark it as visited and enqueue it with an incremented path length. Continue this process until the bottom-right cell is reached. If the queue is exhausted without reaching the destination, return -1.