Breadth-First Search (BFS) explores a graph much like finding connections in a social network. Starting from a source node, it first visits all of its direct friends (neighbors), then all of their friends, and so on, level by level. It uses a queue to keep track of who to visit next, ensuring it doesn't go too deep down one path. This makes it perfect for finding the shortest path in an unweighted graph.
queue = new Queue()
queue.enq(src)
mark src as visited
while queue is not empty:
u = queue.deq()
for each neighbor v of u:
if v is not visited:
queue.enq(v)
mark v as visited
(5 credits)
BFS explores nodes level-by-level in increasing order of distance from the source using a FIFO queue. The first time a target vertex is reached, the path taken must be the minimum edge distance path. DFS delves deep down single branches without distance guarantees.
When graph edge weights are restricted to only 0 or 1, 0-1 BFS uses a Double-Ended Queue (Deque). Weight-0 edges push to the front of the deque (push_front), and weight-1 edges push to the back (push_back). This runs in O(V + E) time, faster than Dijkstra's O((V + E) log V).
Standard BFS searches outwards from source up to distance d, expanding O(bd) nodes (where b is branching factor). Bidirectional BFS runs two simultaneous searches from source and target. They meet in the middle, expanding O(2 * bd/2) nodes, exponentially saving memory and time.
The queue size in BFS reaches the maximum width of the graph (the frontier layer). For complete or dense graphs, the queue can hold O(V) nodes concurrently, consuming high memory compared to DFS which holds only O(H) height nodes.
Sign in to join the discussion
Hand-picked resources to deepen your understanding
© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0