Breadth-first search (BFS)

Learn Algorithms · 3:23

Listen on 93

Lyrics

[Verse 1]
Starting at the root, I mark it visited first
Queue it up, that's where the journey starts
Level by level, spreading out wide
Not going deep, staying side by side
Neighbors get added when their turn comes up
First in first out, filling my cup
Exploring the graph in layers so clean
BFS keeps it systematic and lean

[Chorus]
Queue it up, mark it down, level by level we go
Wide before deep, that's the BFS flow
First in first out, neighbors in line
Shortest path guaranteed every time
Queue it up, mark it down, breadth before height
BFS algorithm, doing it right

[Verse 2]
While the queue ain't empty, I keep the process alive
Dequeue the front node, let the search thrive
Check all adjacents that haven't been seen
Mark them visited, keep the slate clean
Distance from start node, it's always optimal
BFS guarantees paths are not nominal
Unweighted graphs bow down to this might
Finding shortest routes with algorithmic sight

[Chorus]
Queue it up, mark it down, level by level we go
Wide before deep, that's the BFS flow
First in first out, neighbors in line
Shortest path guaranteed every time
Queue it up, mark it down, breadth before height
BFS algorithm, doing it right

[Bridge]
Time complexity big O of V plus E
Space complexity scales with the tree
Web crawling, social networks, maze solving too
BFS handles whatever you throw through
Layer by layer, systematic and true
This algorithm's built for me and you

[Verse 3]
Connected components, it finds them all
Bipartite checking, it won't let you fall
Level order traversal in binary trees
BFS delivers with elegant ease
From source to target, the path that's most short
BFS is the champion of this algorithmic sport

[Chorus]
Queue it up, mark it down, level by level we go
Wide before deep, that's the BFS flow
First in first out, neighbors in line
Shortest path guaranteed every time
Queue it up, mark it down, breadth before height
BFS algorithm, doing it right

[Outro]
When you need the shortest, don't hesitate
BFS will navigate, calculate, and demonstrate
Queue-based exploration, that's the foundation
Breadth-first search, the optimal solution

← Exponential search | What is Dijkstra's Algorithm? →