You are given n x n binary matrix. Find shortest clear path from top-left to bottom-right.
Approach
BFS layer by layer in 8 directions, marking visited by sinking cells.
Time O(n²)Space O(n²)
How it works
1Reject immediately if start or end is blocked.
2BFS expands one ring per step in 8 directions.
3First arrival at the corner is the shortest path.
Sample input / output
Input:
3
0 0 0
1 1 0
1 1 0
Output:
4
Constraints
n == grid.length; 1 <= n <= 100; cells 0/1.
Solution — read it, then walk it
Time O(n²)Space O(n²)Loops 3Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
start / end
statement
condition
loop
returns
definition
1/32
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 →