← Back

Breadth-First Search

graphlevel-ordershortest-path
Press play to start
1function bfs(graph: Record<string, string[]>, start: string): string[] {
2 const visited = new Set<string>();
3 const queue = [start];
4 const order: string[] = [];
5 while (queue.length > 0) {
6 const node = queue.shift()!;
7 if (visited.has(node)) continue;
8 visited.add(node);
9 order.push(node);
10 for (const nb of graph[node] ?? []) {
11 if (!visited.has(nb)) queue.push(nb);
12 }
13 }
14 return order;
15}
Step 1/0

Complexity

Best:O(V+E)
Average:O(V+E)
Worst:O(V+E)
Space:O(V)

Description

Explores a graph level by level, visiting all neighbors before moving deeper. Uses a queue to track the next node to visit.

When to use

Finding shortest paths in unweighted graphs. Level-order traversal. Useful in social networks, GPS navigation, web crawlers.