Loading
Loading
Expand level by level, so the first time you arrive is the shortest way.
Visit a start node, then all its neighbours, then all of theirs, using a queue. Because nodes are reached in order of distance, the first time BFS touches a node it has arrived by a shortest path. On an unweighted graph this is the shortest-path algorithm, and the level structure answers "how many steps" directly.
Mark a node as visited when you enqueue it, not when you dequeue it. Marking on dequeue lets the same node enter the queue several times, which quietly degrades the complexity.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
from collections import deque def shortest_steps(start, is_goal, neighbours): queue = deque([start]) visited = {start} steps = 0 while queue: # Draining exactly one level per iteration is what makes 'steps' # meaningful; without it you cannot tell levels apart. for _ in range(len(queue)): node = queue.popleft() if is_goal(node): return steps for nxt in neighbours(node): if nxt not in visited: visited.add(nxt) # mark on ENQUEUE, not on dequeue queue.append(nxt) steps += 1 return -1 def grid_bfs(grid, start): rows, cols = len(grid), len(grid[0]) queue = deque([start]) seen = {start} while queue: r, c = queue.popleft() for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen: seen.add((nr, nc)) queue.append((nr, nc))| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Paint Bucket Region#91 | Easy | Primary | |
| Unlock Every Vault#93 | Easy | Related | |
| Is There a Route?#95 | Easy | Related | |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in| Medium |
| Primary |
| Shortest Clear Corridor#99 | Medium | Primary |
| Can the Curriculum Be Finished?#102 | Medium | Primary |
| Curriculum Order#103 | Medium | Primary |
| Two-Team Split#104 | Medium | Primary |
| Broadcast Delay#105 | Medium | Related |
| Knight Hops#106 | Medium | Primary |
| Draining to Both Coasts#107 | Medium | Primary |
| Cheapest Trip With Few Layovers#108 | Hard | Related |
| Word Chain#109 | Hard | Primary |
| Corridor With Demolitions#110 | Hard | Primary |