πŸŒ‡DSA
← Back
Data StructureIntermediate
πŸ•ΈοΈ

Graphs (BFS/DFS)

Nodes connected with edges

⏱️ 6–9 hours🧩 10 LeetCode
πŸ”’ Login to unlock solutions and track progress. Login

What is it?

A graph is like a map of cities and roads. Cities are nodes (vertices) and roads are edges.

  • Directed β€” roads are one-way (like Twitter follows)
  • Undirected β€” roads are two-way (like Facebook friends)
  • Weighted β€” roads have a cost/distance
  • Acyclic (DAG) β€” no loops; used for dependency graphs

Real-World Examples

Google Maps navigation
Social network friends
Internet router paths
Package dependencies
Recommendation systems
Maze / game pathfinding

Code Example

What this code shows

BFS from node A on graph A→[B,C], B→[D], C→[D]. Uses a queue: visit A, then queue its neighbours B and C, then visit B (queues D), then C (D already queued), then D. Each node visited exactly once.

const graph = {
A: ["B", "C"], // A connects to B and C
B: ["D"],      // B connects to D
C: ["D"],      // C also connects to D
D: []          // D has no outgoing edges
};

function bfs(start) {
const visited = new Set([start]); // track seen nodes
const queue   = [start];          // process in order

while (queue.length > 0) {
  const node = queue.shift();     // take from front
  console.log(node);             // visit it

  for (const neighbour of graph[node]) {
    if (!visited.has(neighbour)) {
      visited.add(neighbour);    // mark before queuing
      queue.push(neighbour);     // explore later
    }
  }
}
}

bfs("A"); // prints: A  B  C  D

Expected Output

A
B
C
D

LeetCode Practice