๐Ÿ•ธ๏ธ DSA

Graphs, BFS and DFS โ€” The Gentle Introduction

๐Ÿ“… Jul 2, 2026 โฑ 5 min read

Graphs = nodes + connections. Friends networks, city maps, course prerequisites, the web itself. Product companies ask them; service companies rarely โ€” prioritize accordingly.

Representing one

// adjacency list โ€” the standard
const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["D"],
  D: []
};

BFS โ€” explore level by level (queue)

function bfs(start) {
  const queue = [start], seen = new Set([start]);
  while (queue.length) {
    const node = queue.shift();
    for (const next of graph[node])
      if (!seen.has(next)) { seen.add(next); queue.push(next); }
  }
}
// BFS finds SHORTEST path in unweighted graphs โ€” that's its superpower

DFS โ€” go deep first (recursion/stack)

function dfs(node, seen = new Set()) {
  seen.add(node);
  for (const next of graph[node])
    if (!seen.has(next)) dfs(next, seen);
}

The three classics

The seen set is non-negotiable โ€” without it, any cycle = infinite loop.

โ† All Articles