Google · Question 51 · Queues
Shortest Path in Binary Matrix
Problem
Find the shortest clear path from top-left to bottom-right in a binary matrix moving in 8 directions.
Approach
Use BFS to find the shortest path length.
Time O(n²)Space O(n²)
How it works
- 1Check that start and end cells are clear.
- 2Use BFS with distance tracking.
- 3Visit neighbours in 8 directions if unblocked.
- 4Return the distance when the destination is reached.
Sample input / output
Input: 3 0 0 0 1 1 0 1 1 0 Output: 4
Constraints
n == grid.length == grid[i].length; 1 <= n <= 100; cells are 0 or 1.
Solution — read it, then walk it
Time O(n²)Space O(n²)Loops 2Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/28
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits