A2Z Lesson

Log in
← Back to the A2Z sheet

Step 16 Graphs — Theory and traversals

Introduction to Graph

Easy

A graph is a set of vertices connected by edges — the most general structure in this course, since trees, linked lists and grids are all special cases. Graphs model networks, maps, dependencies and states, and nearly every problem in this module is a traversal or a shortest-path variant on one of two representations. This lesson fixes the vocabulary and the representations so the algorithm lessons that follow have solid ground.

Vocabulary

A graph G = (V, E): V vertices (nodes), E edges connecting pairs of them. An edge is undirected (a two-way road) or directed (a one-way street, drawn with an arrow). Edges may carry weights (distances, costs). The degree of a vertex is the number of edges touching it (in-degree and out-degree when directed).

A path is a sequence of vertices joined by edges; a cycle is a path that returns to its start. A graph with no cycles is acyclic — a tree is exactly a connected acyclic undirected graph, equivalently n nodes and n-1 edges. Two vertices are connected if a path joins them; a connected component is a maximal set of mutually connected vertices. A graph where every pair is directly joined is complete. Internalising these words matters because problem statements are written in them: 'provinces', 'islands', 'prerequisites' are components and DAGs in costume.

How problems encode graphs

Three input shapes cover almost everything. (1) n and an edge list — pairs (u, v), sometimes with weights (u, v, w). (2) An adjacency structure given directly. (3) An implicit graph: a grid where each cell is a vertex connected to its up/down/left/right neighbours (islands, flood fill, rotten oranges), or a state graph where vertices are configurations (word ladder).

Also settle indexing early: vertices may be labelled 0..n-1 or 1..n. Mismatching this against your arrays is the single most common cause of graph bugs, so convert once at input time.

Representation 1: adjacency matrix

An n x n table where matrix[u][v] = 1 (or the weight) if edge u-v exists, else 0 / infinity. Checking whether an edge exists is O(1), but the table costs O(n^2) space regardless of how few edges exist, and listing a vertex's neighbours costs O(n) — you must scan its entire row.

Matrices suit dense graphs and small n, and they arise naturally when the input itself is a grid or a matrix (in grid problems you usually do not build the matrix as a graph at all — the grid is the graph, with neighbours computed on the fly).

# adjacency matrix for an undirected unweighted graph n = 5 mat = [[0] * n for _ in range(n)] for u, v in [(0, 1), (1, 2), (2, 3)]: mat[u][v] = 1 mat[v][u] = 1 # undirected: record both directions

Representation 2: adjacency list

For each vertex, store the list of its neighbours (with weights as tuples when needed). Space is O(V + E), listing neighbours of u costs O(degree(u)), and traversals over the whole graph cost O(V + E) — the standard complexity you will quote for BFS and DFS. This is the default representation for this module.

For undirected graphs, add each edge to both endpoints' lists; forgetting the reverse entry silently turns your graph directed and breaks connectivity answers.

def build_adj_list(n, edges): adj = [[] for _ in range(n)] for u, v in edges: # unweighted, undirected adj[u].append(v) adj[v].append(u) return adj def build_weighted_adj_list(n, edges): adj = [[] for _ in range(n)] for u, v, w in edges: # directed, weighted adj[u].append((v, w)) return adj

Traversal mental model and common mistakes

Two traversals organise everything. BFS explores level by level with a queue — on unweighted graphs it also yields shortest paths in edges. DFS dives down one path with a stack or recursion — natural for components, cycles and topological order. Both mark vertices in a visited array the moment they are enqueued/pushed (not when popped), or the same vertex gets queued many times.

Common mistakes: (1) forgetting the visited array entirely and looping forever on the first cycle; (2) marking visited at pop time, flooding the queue with duplicates; (3) adding undirected edges in one direction only; (4) 0-index vs 1-index mismatches between the edge list and your arrays; (5) running a traversal from vertex 0 only and missing other components — wrap it in a loop over all vertices.

Key points

  • Graph = vertices + edges; directed vs undirected and weighted vs unweighted are the first two questions to ask of any problem.
  • A tree is a connected acyclic graph: n vertices, n-1 edges — graph algorithms generalise tree ones.
  • Adjacency list is the default: O(V + E) space and traversal. Adjacency matrix: O(1) edge check but O(V^2) space.
  • Undirected edges go into both endpoints' lists; directed edges go in one.
  • Visited must be marked when a vertex is enqueued, and traversals must be restarted for every unvisited component.

Suggested questions

Traversal Techniques ↗ BFS and DFS implemented on the adjacency list you built in this lesson.
Connected Components ↗ Restart a traversal from every unvisited vertex and count the restarts.
Number of provinces ↗ Components where the input arrives as an adjacency matrix instead of a list.
Number of islands ↗ The implicit grid graph: cells are vertices, neighbours computed on the fly.
Detect a cycle in an undirected graph ↗ Your first traversal-with-memory problem: a visited neighbour that is not your parent means a cycle.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.