█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Computer Science Fundamentals/Data Structures/Graphs
50 minIntermediate

Graphs

After this lesson, you will be able to: Represent graphs with adjacency lists and matrices, distinguish directed/undirected and weighted/unweighted graphs, and implement BFS and DFS from scratch.

A graph is the most general data structure: nodes connected by edges. Social networks, maps, dependencies, the web itself are all graphs. Mastering graph representation and traversal unlocks a huge class of real problems and interview questions.

Prerequisites:Heaps

What a graph is

A graph is a set of vertices (nodes) connected by edges (links). Edges can be directed (a one-way follow on social media) or undirected (a mutual friendship). They can be weighted (a road with a distance or cost) or unweighted (just connected or not). Trees and linked lists are actually special cases of graphs. Once you can model a problem as a graph, decades of graph algorithms become available to you.

Two ways to represent a graph

Adjacency list (usually preferred) vs adjacency matrix.

tsx
# Adjacency list: for each node, a list of its neighbors.
# Space O(V + E). Best for sparse graphs (most real graphs).
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": [],
}
# Adjacency matrix: a V x V grid; matrix[i][j] = 1 if edge i->j.
# Space O(V^2). Edge lookup is O(1) but wasteful for sparse graphs.
# A B C D
# A [ 0, 1, 1, 0 ]
# B [ 0, 0, 0, 1 ]
# C [ 0, 0, 0, 1 ]
# D [ 0, 0, 0, 0 ]

BFS and DFS

The two fundamental traversals. BFS uses a queue; DFS uses a stack or recursion.

python
from collections import deque
def bfs(graph, start): # explores ring by ring (shortest path in edges)
visited, q, order = {start}, deque([start]), []
while q:
node = q.popleft()
order.append(node)
for nbr in graph[node]:
if nbr not in visited:
visited.add(nbr)
q.append(nbr)
return order
def dfs(graph, start, visited=None, order=None): # goes deep first
if visited is None: visited, order = set(), []
visited.add(start)
order.append(start)
for nbr in graph[start]:
if nbr not in visited:
dfs(graph, nbr, visited, order)
return order

💡 BFS vs DFS: when to use which

Use BFS when you need the shortest path in an unweighted graph or want to explore level by level (nearest first). Use DFS when you need to explore all paths, detect cycles, do topological sorting, or find connected components. The single most common graph bug is forgetting the visited set: without it you revisit nodes and loop forever on any graph with a cycle.

Where graphs show up in real systems

Maps and navigation (shortest path). Social networks (friend suggestions, degrees of separation). Dependency resolution (npm, build systems, course prerequisites) which need topological sort. Web crawling and PageRank. Recommendation engines. Network routing. When a problem involves relationships, connections, or 'can I get from here to there,' it is almost certainly a graph problem.

Common mistakes only experienced devs catch

Forgetting the visited set and looping forever on a cyclic graph. Using an adjacency matrix for a large sparse graph and wasting O(V squared) memory. Confusing BFS (queue, shortest unweighted path) with DFS (stack/recursion, deep exploration). Assuming BFS gives the shortest path on a weighted graph (it does not; you need Dijkstra). Recursing DFS on a graph with millions of nodes and overflowing the stack (use an explicit stack).

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Heaps
Back to Data Structures
Tries→