BFS was the right call and I knew it immediately, but I fumbled the complexity explanation.
Use BFS from the start cell, exploring all four directions level by level, because BFS guarantees the shortest path in an unweighted grid. Track visited cells to avoid cycles, and return the distance when the target is reached, or -1 if the queue empties.
Pro tip: Mention that you can optimize space by using a 2D array of distances or by modifying the grid in-place to mark visited cells, but clarify that modifying input may not be allowed. Also, discuss early termination when the target is found.
Confirm grid dimensions, start and target coordinates, and that start and target are within bounds and not blocked. If invalid, return -1 immediately.
Use a queue for BFS, starting with the start cell. Maintain a visited set or a distance grid to track visited cells and distances.
While the queue is not empty, dequeue a cell, check if it's the target, and if not, enqueue all valid unvisited neighbors (up, down, left, right) with distance+1.
If target is reached, return the distance. If queue empties without reaching target, return -1.
Time complexity is O(m*n) since each cell is visited at most once. Space complexity is O(m*n) for the queue and visited set in the worst case.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.