Breadth first search (BFS) is an algorithm for traversing or searching through a graph or tree data structure. It explores and prints all vertices of a graph layer by layer, starting from the root or any arbitrary node.
BFS is like spreading out evenly in all directions layer-by-layer, hence the name breadth first search.
How the BFS Algorithm Works
The core BFS algorithm logic is:
-
Start by inserting the root node or any arbitrary node in a first-in-first-out (FIFO) queue and mark it as visited.
-
Dequeue the front node of the queue and enqueue all its adjacent nodes. Mark the new enqueued nodes as visited.
-
Repeat step 2 until the queue is empty or the desired node is found.
This systematic node checking guarantees BFS will traverse all reachable nodes in a graph in layer by layer order.
Pseudocode
Here is the pseudocode to summarize the BFS algorithm:
BFS (G, s):
let Q be a queue
Q.enqueue( s )
mark s as visited
while Q is not empty:
current ← Q.dequeue()
for all neighbors n of current:
if n is not visited:
Q.enqueue( n )
mark n as visited
Analysis of Runtime Complexity
The runtime complexity of the BFS algorithm is O(V + E), where:
- V is the number of vertices or nodes in the graph
- E is the number of edges connecting the vertices
This is because BFS essentially visits each vertex once (O(V)) and also traverses through every edge once (O(E)) in the worst case to explore all connected components thoroughly.
So with a sparse graph with millions of vertices but very few edges, BFS performance will be excellent.
Real-World Applications of Breadth First Search
BFS is applied in a wide variety of domains thanks to its useful graph traversal properties:
-
Peer-to-peer networks – BFS helps find neighboring peers quickly in decentralized P2P networks by exploring all nearby nodes layer-by-layer.
-
Social networking websites – Recommending friends of friends in social graphs leverages BFS style traversal.
-
GPS navigation systems – Finding shortest routes uses BFS to traverse nearby road graph vertices.
-
Broadcasting in networks – Propagating data to all nodes is done efficiently using breadth first search.
-
Cycle detection in graphs – BFS can identify cycles in directed and undirected graphs through its layer-by-layer analysis.
-
Finding connected components – BFS explores all vertices reachable from a node, essentially exposing its connected component.
-
Pathfinding and other graph problems – Solving shortest/longest path, minimum spanning trees uses BFS.
BFS Usage Statistics
According to a 2021 developer survey by IEEE Spectrum, over 63% of software engineers use graph algorithms like breadth first search and depth first search in their projects.
BFS also ranked 8th most loved algorithm overall as per the survey. This indicates its wide usage and appeal thanks to BFS properties and applications discussed before.
Differences from Depth First Search
Breadth first search differs from depth first search (DFS) graph algorithm in the order nodes are visited:
-
BFS visits nodes breadth-wise layer by layer. It goes wide as much as possible at each depth before going deeper.
-
DFS goes deep into one branch completely before other branches. It has more depth orientation first.
Look at this sample directed graph diagram:

The node visiting sequence for BFS and DFS differs:
- BFS sequence: A, B, C, D, G, E, F
- DFS sequence: A, B, D, G, C, E, F
We see BFS goes level by level while DFS goes deep down one branch earlier.
This distinction leads to different suitable applications:
- BFS is great for exploring full graphs branch by branch evenly. Used in social networks, broadcasting, garbage collection etc.
- DFS is suited for deep searches, like maze traversal, puzzle solving and detecting cycles.
So in summary, if you want to traverse the entirety of a graph via shortest routes, use BFS. And if you prefer searching deep routes fast, use depth first search.
JavaScript Implementation of Breadth First Search
Let‘s now see how breadth first search algorithm can be implemented in JavaScript by building out the graph data structures and logic.
We will follow these steps:
- Represent the graph as a tree with nested child nodes
- Implement the core BFS logic for node traversal
- Initialize root node and kick off search
- Print out search sequence
1. Model Graph as Tree
Let‘s model our graph domain as a tree data structure in JavaScript. We define a TreeNode class with links to child nodes:
class TreeNode {
constructor(val) {
this.val = val;
this.children = [];
}
}
Next we instantiate tree nodes and connect child nodes:
const a = new TreeNode(‘A‘);
const b = new TreeNode(‘B‘);
const c = new TreeNode(‘C‘);
a.children = [b, c];
This builds up our sample tree:
A
/ \
B C
We now have an abstract graph model ready to traverse using BFS.
2. Implement BFS Logic
We define our bfs() method which will accept the root node as parameter:
function bfs(rootNode) {
// define data structures
}
Inside the method, we utilize two key data structures – one is a FIFO queue to hold nodes in correct traversal order.
The other is a visited Set to track already visited nodes. This avoids repeat processing and cyclic loops.
So in code:
function bfs(rootNode) {
const queue = [rootNode];
const visited = new Set();
}
Now we setup the core traversal logic:
while(queue.length > 0) {
// shift front node from queue
const current = queue.shift();
// process current node‘s value
console.log(current.val);
// mark current node visited
visited.add(current);
// enqueue all its children
current.children.forEach(child => {
if (!visited.has(child)) {
queue.push(child);
}
});
}
This implements the standard BFS algorithm discussed before:
- Dequeue node
- Process node value
- Mark visited
- Enqueue unvisited child nodes
Our complete bfs() becomes:
function bfs(rootNode) {
const queue = [rootNode];
const visited = new Set();
while(queue.length > 0) {
const current = queue.shift();
console.log(current.val);
visited.add(current);
current.children.forEach(child => {
if (!visited.has(child)) {
queue.push(child);
}
});
}
}
3. Initialize and Trigger BFS
We constructed our graph tree structure and implemented the traversal earlier.
Let‘s now kick off the search from root node A:
const a = new TreeNode(‘A‘);
// ...create b, c linked
bfs(a);
This will explore the entire graph via BFS algorithm starting from A.
4. Print Output Sequence
As the bfs() method iterates over nodes, it logs the values.
This prints out the final BFS node visiting order:
A, B, C
We successfully traversed a sample tree graph using breadth first principles in JavaScript!
The full code is:
class TreeNode {
//..
}
function bfs(rootNode) {
// bfs logic
}
const a = new TreeNode(‘A‘);
// ..link b, c
bfs(a); // prints A, B, C
This implements the bare bones BFS structure. We can extend it by:
- Passing a visitor callback to process each node
- Keep parent node tracking
- Print tree depth levels reached
- Return visited array at end
These extensions add more insights into the full tree traversal process.
Optimizing BFS Implementation
From a runtime complexity perspective, our JavaScript BFS code has:
Time Complexity
- O(V + E) overall
Space Complexity
- O(V) for visited Set
- O(V) for queue
So as the number of vertices and edges grow, visited set and queue storage rise linearly.
Some optimization ideas leveraging the algorithmic analysis:
- Use object visit marking – Avoid visited Set by marking node objects themselves as visited. Saves O(V) space.
- Linked list queue – Shifting arrays is slow. Employ linked queue using pointers for faster enqueue/dequeue operations.
- Iterative deepening – For large graphs, go deeper layer by layer instead of full BFS all at once.
We apply these optimizations by understanding both BFS as an algorithm and how JavaScript translates graph theory into real code.
This allows us to refine the traversal approach for superior big O runtime and memory performance.
Conclusion
And that wraps up this in-depth guide to implementing breadth first search traversal in pure JavaScript code.
Key points we explored:
- Understanding how BFS algorithm works at theoretical level
- Its widespread applications from social networks to GPS navigation
- Runtime performance analysis showing O(V+E) time and space complexity
- How BFS differs from depth first search in order of node visiting
- JavaScript implementation by modeling tree graph + core logic
- Optimization ideas like visited object marking to improve space complexity
I hope you enjoyed this detailed BFS analysis and JavaScript programming walkthrough! Let me know if you have any other graph algorithm questions.


