Breadth-First Search visualization
Explore level by level with a queue — gives shortest paths in unweighted graphs.
BFS visits every vertex at distance 1, then distance 2, and so on. A FIFO queue guarantees that order.
Marking a node visited when it is enqueued (not when dequeued) prevents the same node from entering the queue twice.
Complexity
Time: best O(V + E), average O(V + E), worst O(V + E). Space: O(V). Difficulty: Beginner.
Pseudocode
procedure BFS(G, s):
dist[s] ← 0; queue ← [s]; visited ← {s}
while queue not empty:
u ← queue.dequeue()
for each neighbor v of u:
if v not visited:
visited.add(v); dist[v] ← dist[u] + 1
queue.enqueue(v)
nodes never visited are unreachable (dist = ∞)More graphs algorithms
- Depth-First Search — Go as deep as possible along each branch before backtracking.
- Dijkstra's Shortest Path — Greedily settle the closest unsettled vertex using a priority queue.
- Bellman–Ford — Relax every edge V−1 times; handles negative weights and detects negative cycles.
- Prim's MST — Grow one tree by always adding the cheapest edge leaving it.
- Kruskal's MST — Sort edges by weight and add each one unless it would create a cycle (union–find).
- Topological Sort (Kahn) — Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.
- Floyd–Warshall — All-pairs shortest paths by allowing one more intermediate vertex k at a time.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.