Skip to content
Guest
Learn DSA · Course Syllabus Show lessons
Graphs & Greedy · 9 min read · Intermediate

Graphs, Adjacency Lists & Shortest Path BFS

Model networks and dependencies with adjacency lists, track visited nodes to prevent infinite loops, and find shortest paths with BFS.

What you'll learn

  • Represent sparse graphs cleanly using an adjacency list (Map<Node, Node[]>)
  • Prevent infinite cycles by marking nodes in a visited Set when enqueuing
  • Compute shortest unweighted path length in O(V + E) using BFS

Unlike trees, graphs can contain cycles and disconnected components. Always maintain a visited Set (and add each neighbor to visited the moment you enqueue it, not when you dequeue it!) so BFS runs in linear $O(V + E)$ time.

Fill-in-the-Blank Exercise

Visited Guard in Graph BFS

Skip already-visited neighbors and mark new neighbors before enqueuing.

for (const next of graph[node]) {
if (!visited.(next)) {
  visited.(next);
  queue.push([next, dist + 1]);
}
}

Live DSA Playground

Shortest Path Hops via Graph BFS
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What is the time complexity of Breadth-First Search on a graph represented by an adjacency list with V vertices and E edges?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind