Find Shortest Clear Grid Path
Company: Snapchat
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Given an `n x n` binary grid, where `0` means open and `1` means blocked, return the length of the shortest clear path from the top-left cell to the bottom-right cell.
You may move in all 8 directions to neighboring cells: horizontal, vertical, and diagonal. A valid path may only pass through open cells.
Return `-1` if either endpoint is blocked or no path exists.
### Constraints & Assumptions
- The path length counts the number of cells visited, including the start and end cells.
- The grid is square: `n x n`.
- Diagonal moves are allowed.
- Mutating the grid for visited marking is acceptable if stated, but a separate visited set is also fine.
- Use breadth-first search because all moves have equal cost.
### Clarifying Questions to Ask
- Does path length count edges or cells?
- Are diagonal moves allowed through corners if adjacent orthogonal cells are blocked?
- Can I mutate the input grid?
- What should be returned for an empty grid?
### What a Strong Answer Covers
- Endpoint-blocked checks.
- BFS from `(0, 0)`.
- 8-direction neighbor generation.
- Visited marking to avoid cycles.
- First time reaching bottom-right gives shortest path.
- Time and space complexity.
### Follow-up Questions
- How would the solution change if moves had different costs?
- How would you return the actual path, not only length?
- How would you handle a rectangular grid?
- How would you solve it if diagonal corner-cutting were disallowed?
Quick Answer: Solve the shortest clear path in an n by n binary grid using BFS in 8 directions. Covers blocked endpoints, visited marking, path length, correctness, complexity, and weighted-move follow-ups.
Return the shortest 8-directional clear path length from top-left to bottom-right, counting cells visited. Return -1 if blocked or unreachable.
Constraints
- Inputs are Python literals matching the function signature.
- Return a deterministic exact-match value.
Examples
Input: ([[0,1],[1,0]],)
Expected Output: 2
Explanation: Diagonal move reaches the end.
Input: ([[0,0,0],[1,1,0],[1,1,0]],)
Expected Output: 4
Explanation: Path around obstacles.
Input: ([[1]],)
Expected Output: -1
Explanation: Blocked start.
Input: ([[0]],)
Expected Output: 1
Explanation: Single open cell.
Hints
- Pick a representation that makes the requested operation direct.
- Handle empty inputs and boundary cases first.