QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Advanced 22 min readModule: Module 9: Graph Representations, BFS & DFS

Graph Traversal: BFS (Shortest Path) & DFS

Represent graphs via adjacency lists and traverse networks using BFS (Queue) and DFS (Stack/Recursion).

What You Will Learn in This Lesson

  • Adjacency list vs adjacency matrix memory tradeoffs
  • Breadth-First Search (BFS) using a Queue to find shortest paths in unweighted graphs
  • Depth-First Search (DFS) for connected components and cycle detection

Introduction & Core Concept

A Graph is a non-linear data structure consisting of vertices (nodes) and edges that connect pairs of vertices.
WHY DOES THIS MATTER IN THE REAL WORLD?

Graphs model social networks (friend connections), maps (GPS navigation), recommendation engines, and dependency trees.

Breadth-First Search (BFS) on Graph

javascript
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const traversal = [];
while (queue.length > 0) {
const node = queue.shift();
traversal.push(node);
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return traversal;
}
const graph = { A: ["B", "C"], B: ["D"], C: ["E"], D: [], E: [] };
console.log("BFS Order:", bfs(graph, "A"));

Line-by-Line Technical Breakdown

1Always track visited nodes with a Set to prevent infinite loops in cyclic graphs.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[JAVASCRIPT]
JAVASCRIPT SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Use BFS for shortest path in unweighted graphs; use DFS for topological sorting.

Lesson Summary & Core Takeaways

  • BFS and DFS form the foundation of all network and pathfinding algorithms.