Binary Matrix
Current Cell
-
Distance
-
Queue Size
0
Shortest Path
-
BFS Queue
Empty
Click "Step" or "Play" to find the shortest path from (0,0) to (n-1,n-1)
Blocked (1)
Clear (0)
Start
Goal
Current
Visited
Path
Python Code - BFS Approach
if grid[0][0] != 0 or grid[n-1][n-1] != 0:
return -1
queue = deque([(0, 0, 1)]) # (row, col, distance)
while len(queue) > 0:
i, j, dist = queue.popleft()
if in_bounds and grid[i][j] == 0 and not visited[i][j]:
visited[i][j] = True
if i == n-1 and j == n-1: return dist
for di, dj in directions: # 8 directions
queue.append((i+di, j+dj, dist+1))
return -1 # no path found