Graphs: concepts, connectivity and traversals
A rigorous introduction to graphs: definitions, degrees, representations, isomorphism, paths and connectivity, including strong connectivity in directed graphs; directed acyclic graphs and partial orders; breadth-first and depth-first traversal trees; and certificates for bipartite and Eulerian graphs.
After this lesson you can
- Model problems with graphs and digraphs and choose a representation.
- Use powers of the adjacency matrix to count walks of length k.
- Decide isomorphism in small cases and use invariants to disprove it.
- Describe BFS and DFS trees and their properties, including distance layers and back edges.
- Characterize bipartite and Eulerian graphs and produce the appropriate certificate in each case.
Before you start
Motivation: one structure, many problems
Four situations that appear to have nothing in common:
- Dependencies. A package manager must install each library after those it needs, and a build system must recompile exactly what depends on a modified file. If dependencies form a cycle, no ordering exists; the cycle must be detected and located. The computation graph PyTorch constructs when running a model is similar: backpropagation traverses it in reverse order.
- Call graphs. In static security analysis, the question “can user-controlled data reach this dangerous function?” reduces, in its simplest form, to whether one vertex is reachable from another in the call graph. A concrete path witnessing the answer makes it useful for correcting the flaw.
- Knowledge graphs. A triple (subject, relation, object) is a labelled edge. A question requiring three linked facts is a walk of length 3, and counting or enumerating such walks is matrix algebra.
- Molecules. Butane and isobutane have the same formula, , but their carbon skeletons are a chain and a star. Deciding whether two molecules are the same means deciding whether two graphs are isomorphic, exactly the distinction a graph neural network must make to predict chemical properties.
In all four cases the information lies in who connects to whom, not where things are or how large they are. That abstraction is a graph. This lesson establishes the vocabulary rigorously (there are three distinct notions of a route, and confusing them causes real errors), representations and what linear algebra says about them, isomorphism and its invariants, connectivity in directed and undirected graphs, the relationship between acyclic graphs and partial orders, breadth-first and depth-first traversals as mathematical objects, and two classic characterizations of bipartite and Eulerian graphs. Each has a property worth noticing now: whether yes or no, the answer comes with a certificate anyone can check.
Intuition: a relation you can draw
A directed graph is simply a binary relation on a finite set, drawn with points and arrows; an undirected graph is a symmetric, irreflexive relation with one line per pair . Almost every question starts with counting. Draw some graphs and see what changes and what does not.
Three observations proved in the rest of the lesson:
- The sum of degrees is always twice the number of edges, because each edge is counted once at each endpoint. Consequently, the number of odd-degree vertices is always even.
- Entry of counts walks from to with exactly steps, including those that go back and forth along the same edge. That is why the counts grow so quickly: they are not paths.
- In a digraph, “connected” splits into two notions. The sandbox’s example digraph is one piece if directions are ignored, but no other vertex is reachable from vertex 6: it has one weak component and three strong ones.
Graphs, multigraphs, and digraphs
If , vertices and are adjacent or neighbors, and the edge is incident to both. The neighborhood of is , and its degree is its number of incident edges, : in a simple graph this is , while a multigraph counts each parallel edge separately. In a digraph distinguish out-degree (arcs with tail ) from in-degree . The degree sequence lists degrees from largest to smallest.
A few families appear repeatedly and are worth keeping handy:
| Family | Vertices | Edges | Degrees |
|---|---|---|---|
| complete | all | ||
| cycle () | all 2 | ||
| path | two of degree 1, the rest 2 | ||
| complete bipartite | on one side, on the other | ||
| hypercube | (-bit words) | all (neighbors differ in one bit) |
The name comes from a party: if each guest counts their handshakes, the total is even because each handshake is counted by two people. The proof is a double count of pairs (vertex, incident edge), which you will work through in the first guided exercise. The directed version is even more direct: each arc has exactly one tail and one head. The corollary about odd vertices looks like a curiosity but is the key to Euler’s theorem at the end of the lesson.
A subgraph of is a graph with and . It is induced by , written , if it contains all edges of with both endpoints in ; it is spanning if . The complement has the same vertices and exactly the edges missing from . The distinction matters: is a subgraph of , but no induced subgraph of is an .
Representations and what they count
The choice is an engineering tradeoff. The matrix occupies entries even with few edges and answers “is an edge?” in constant time; lists use space proportional to and traverse neighbors of in time proportional to . Real graphs are nearly always sparse (: a social network with users and a few hundred friends per person), so algorithms use lists or sparse formats such as CSR or coordinate pairs (COO), as scipy and graph neural network libraries do internally. See representation costs for the cost analysis. The matrix, however, opens the door to linear algebra, which we exploit next.
Walks, trails, and paths
Every path is a trail and every trail is a walk; the inclusions are strict. Length counts edges, not vertices. In a digraph, cycles of length 1 (loops) and 2 () are valid.
Proof
Use induction on . For , and the only length-0 walk stays put, from to . Assume the claim for . Every walk of length from to decomposes uniquely into a walk of length from to some , followed by an edge from to . For fixed there are choices for the first part and for the edge. Summing over by the sum rule gives
which is the definition of matrix multiplication.
∎The theorem turns combinatorial questions into matrix calculations. For a simple undirected graph:
- : a closed walk of length 2 goes to a neighbor and back. Thus , the handshaking lemma again.
- , where is the number of triangles: each triangle gives 6 closed walks of length 3 (3 starting vertices times 2 directions). No other closed walks of length 3 exist because there are no loops.
- with counts common neighbors of and , the basis of many recommendation heuristics (“friends of friends”).
Another consequence: is reachable from if and only if there is a walk from to , and, as we will soon see, if there is one, there is one of length at most . Thus, is reachable from if and only if . The reachability relation is the reflexive and transitive closure of the arc relation, and this formula computes it using matrix products (in Boolean arithmetic, to avoid overflow).
Isomorphism and invariants
Two drawings can represent the same graph with renamed vertices. Here is the precise notion.
The condition requires both implications: preserving edges and non-edges alike. A bijection that only maps edges to edges can go from to , which are not isomorphic.
Deciding isomorphism by trying the bijections becomes infeasible from onward. To disprove it takes much less: an invariant is any quantity that agrees for isomorphic graphs, so if it differs, the graphs are not isomorphic.
Proof
An isomorphism maps the neighborhood of bijectively to that of , so it preserves degrees; applied vertex by vertex, it maps walks to walks, paths to paths, and cycles to cycles of the same length, giving the combinatorial claims. For the algebraic claims: if with a permutation matrix, then and is similar to : they have the same characteristic polynomial, hence the same spectrum and traces of all powers.
∎No invariant in that list is complete: in each case nonisomorphic graphs can share it. Three useful pairs are:
| Pair | Agree on | Distinguished by |
|---|---|---|
| and the triangular prism | , , all degrees 3, connected | triangles: 0 versus 2; bipartiteness; spectrum |
| and two disjoint triangles | , , all degrees 2 | connectedness; triangles; spectrum |
| star and plus an isolated vertex | spectrum: | degree sequence |
The third is the smallest example of cospectral graphs: the spectrum, which seems like a fingerprint, does not determine the graph. The next cell computes invariants for the three pairs and searches for isomorphisms by backtracking: it assigns vertices one at a time, only to vertices of the same degree, and stops as soon as an adjacency or non-adjacency disagrees with those already assigned.
import numpy as np
def adj(n, edges):
A = np.zeros((n, n), dtype=int)
for u, v in edges:
A[u, v] = A[v, u] = 1
return A
def invariantes(A):
"""Invariantes baratos: si alguno difiere, los grafos no son isomorfos."""
A3 = np.linalg.matrix_power(A, 3)
return {
"m": int(A.sum()) // 2,
"grados": tuple(int(g) for g in sorted(A.sum(axis=1), reverse=True)),
"triángulos": int(np.trace(A3)) // 6,
"espectro": tuple(float(x) for x in np.round(np.linalg.eigvalsh(A), 4) + 0.0),
}
def isomorfismos(A, B, todos=False):
"""Biyecciones f con A[u, w] = B[f(u), f(w)], extendiendo una asignación parcial con retroceso."""
n = len(A)
if n != len(B):
return []
gA, gB = A.sum(axis=1), B.sum(axis=1)
f, usado, sols = [-1] * n, [False] * n, []
def extender(u):
if u == n:
sols.append(f.copy())
return not todos # True = parar en la primera
for x in range(n):
if usado[x] or gA[u] != gB[x]:
continue
# coherencia con lo ya asignado: adyacencias y no adyacencias
if all(A[u, w] == B[x, f[w]] for w in range(u)):
f[u], usado[x] = x, True
if extender(u + 1):
return True
f[u], usado[x] = -1, False
return False
extender(0)
return sols
K33 = adj(6, [(i, j) for i in range(3) for j in range(3, 6)])
prisma = adj(6, [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)])
C6 = adj(6, [(i, (i + 1) % 6) for i in range(6)])
dosK3 = adj(6, [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)])
estrella = adj(5, [(0, i) for i in range(1, 5)])
C4K1 = adj(5, [(0, 1), (1, 2), (2, 3), (3, 0)])
petersen = adj(10, [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
+ [(5 + i, 5 + (i + 2) % 5) for i in range(5)])
for nombre, M in [("K3,3", K33), ("prisma", prisma), ("C6", C6), ("2 K3", dosK3), ("estrella", estrella), ("C4 + K1", C4K1)]:
print(f"{nombre:9s}", invariantes(M))
print("\nisomorfismos K3,3 -> prisma:", len(isomorfismos(K33, prisma, todos=True)))
for nombre, M in [("K3,3", K33), ("prisma", prisma), ("C6", C6), ("Petersen", petersen)]:
print(f"automorfismos de {nombre}: {len(isomorfismos(M, M, todos=True))}")The automorphism count measures each graph’s symmetry: has (permuting each side and swapping them), the prism and have 12, and the Petersen graph has 120. Pruning by degree and consistency makes the search explore a tiny fraction of Petersen’s bijections.
Paths, connectivity, and components
A walk can take unnecessary detours; if reaching the destination is what matters, they can always be removed.
Proof
By the well-ordering principle, among the walks from to formed from edges of the given walk there is one of minimum length, . If it repeated a vertex, with , the walk would be shorter and of the same kind. Therefore its vertices are distinct: it is a path. Since it has distinct vertices, .
∎In a connected undirected graph, is a distance in the metric sense: it is symmetric, vanishes only at , and satisfies the triangle inequality, because concatenating a path from to and another from to gives a walk from to . In a digraph, and can differ (and one can be infinite).
Proof
Use induction on , removing and replacing an edge. Without edges, each vertex is its own component: . Adding an edge to a graph leaves the components unchanged if and were already in the same one; otherwise it merges exactly two into one. In both cases falls by at most 1 when increases by 1, so is preserved.
∎Equality holds exactly when no edge is added within an already formed component, that is, when the graph has no cycles: it is a forest. This is one of the characterizations of trees in the next lesson.
Strong connectivity and the condensation graph
In a digraph, weak connectivity says the network is in one piece if directions are ignored; strong connectivity says every point can reach every other point. The digraph , is weakly connected, but no edge leaves 4: it has two SCCs, and . Contracting each SCC to a point leaves a very specific structure.
Proof
If there were a cycle with , each vertex of could reach every vertex of (within an SCC every vertex is reachable, and there is an arc between the two), and vice versa by traversing the rest of the cycle. The vertices of and would be strongly connected and belong to the same component.
∎Every digraph is therefore a DAG of strongly connected blocks. This decomposition is used by 2-SAT solvers (a formula is unsatisfiable exactly when a variable and its negation fall in the same SCC of the implication graph), compilers analyzing loops, and incremental computation engines, which recompute an entire SCC when something inside changes and respect the DAG order between them. The linear-time algorithm for computing them is the strongly connected components algorithm; here you will implement it with two depth-first searches.
Directed acyclic graphs and partial orders
A vertex with no incoming arcs is a source and one with no outgoing arcs is a sink.
Proof
If no vertex were a source, we could keep moving backwards forever: from there is an arc , from another , and so on. Among there are vertices, so by the pigeonhole principle one repeats, with , and is a closed directed walk containing a directed cycle (apply the preceding section’s argument to the closed walk: its shortest closed subwalk does not repeat vertices). The sink follows similarly, moving forwards.
If there is a topological order and a cycle , the positions of the would strictly increase around the cycle and return to the starting position: impossible. Conversely, use induction on : a DAG with vertices has a source ; removing it leaves a DAG, which by the induction hypothesis has a topological order; placing at the front gives one for the whole graph, because no arc enters .
∎The proof is an algorithm (Kahn’s: remove sources one at a time) and so is its contrapositive: if at some point no source remains, what remains contains a cycle, which can be found by following incoming arcs backwards. A topological order is rarely unique, and the number of such orders has a meaningful interpretation: the number of valid ways to schedule the tasks.
The connection with order relations is exact. Given a DAG , define if is reachable from .
Proof
is reflexive and transitive by construction (walks of length 0 and concatenation). It is antisymmetric: if and with , concatenating the two walks yields a closed directed walk of positive length, which contains a cycle. A total order on extends if and only if it respects every arc, because the arcs generate by transitivity; that is the definition of a topological order, so the linear extensions of are the topological orders. Conversely, the Hasse diagram of a finite order has an arc when covers ; it is acyclic because its arcs strictly increase in the order, and in a finite order every relation decomposes into a chain of cover relations.
∎Different DAGs can have the same reachability: adding the arc when already exist changes nothing. Among them, the Hasse diagram is the unique one with the fewest arcs, the transitive reduction (Aho, Garey and Ullman, 1972). A build system drawing “direct” dependencies ideally draws this reduction.
Traversals: BFS and DFS as objects
Traversing a graph means discovering its vertices by following edges from a root . The general scheme maintains a set of discovered vertices and a frontier of discovered vertices whose edges have not yet been examined: remove a vertex from the frontier, examine its edges , and whenever is new, discover it, record its parent , and add it to the frontier.
Counting shows that the result is a tree: every discovered vertex other than contributes exactly one edge (its parent’s), and the parent was discovered before the child, so following parents from any vertex ends at without repetition. In an undirected graph it is a spanning tree of the component of ; in a digraph, it is a tree whose arcs point away from the root and cover what is reachable from .
The BFS tree measures distances
Proof
First, a property of the queue: at all times the layers of the vertices it contains are in nondecreasing order and differ by at most 1. This holds initially (only ) and is preserved because the first vertex, at layer , is removed and vertices at layer are added at the end. Thus vertices leave the queue in nondecreasing layer order.
Now because the tree path from to has length . For the other inequality, use strong induction on . If , . If , let be the penultimate vertex of a shortest path from to ; and by hypothesis . When leaves the queue and examines edge , either is new and receives , or it was already discovered by a vertex that left before , with , and then .
The edge claim follows from the triangle inequality: if , , and in the undirected case the reverse holds too.
∎The edges outside an undirected graph’s BFS tree thus come in two kinds: same-layer or next-layer edges. The first are the important ones: if joins two vertices in the same layer , the tree branches from and to their first common ancestor have the same length and, together with , form a cycle of odd length . This observation is half the proof of the bipartite graph theorem.
The DFS tree and parenthesis structure
DFS uses a clock that advances when a vertex is discovered () and when it is finished (, when it has no edges left to examine). While is on the stack, between and , it is called gray; before that, white; afterward, black.
Proof
The stack never reorders: if is pushed while is on it, is above (it is its descendant, because each vertex is pushed above its parent) and leaves first. This gives the parenthesis structure and the characterization of descendants. For the white path, the forward direction is clear: the tree path from to is white at . For the converse, suppose some vertex on the white path does not become a descendant and let be the first. Then is a descendant of (or is ) and ; since examines the edge to before finishing, is discovered before and after because it was white at that time. Thus , and by the parenthesis structure the interval of lies inside that of : it is a descendant. Contradiction.
∎This result is at the heart of DFS theory, and its algorithmic version is the parenthesis theorem. The edge classifications follow from it. An edge examined from to that is not in the tree is a back edge if is an ancestor of (it is gray), a forward edge if it is an already finished descendant, and a cross edge if is in another, already finished branch.
Proof
(a) Let be an edge and suppose . At , is white and is a white path, so is a descendant of : the edge joins ancestor and descendant. DFS forests have edges (each component contributes a tree with one more vertex than edges), and all other edges are back edges. Each back edge , together with the tree path from to , forms a cycle; and if there are none, the graph is its DFS forest.
(b) A back edge and the tree path from to form a cycle. Conversely, let be a cycle, its first discovered vertex, and the arc of entering . At , the rest of is a white path from to , so is a descendant of and, when examines , is still gray: it is a back edge. For the order: if there are no back edges, when an arc is examined, is white (and will be a descendant, with ) or black (also with ). Every arc goes from greater to smaller .
∎The number is the graph’s cyclomatic number, the dimension of its cycle space: each back edge contributes an independent cycle. In the figure, the “back edges” reading checks this live. The cost of both traversals, with adjacency lists, is analyzed in the algorithms module, and their use as search strategies in enormous state spaces that do not fit in memory is covered in breadth-first search and depth-first search.
Bipartite graphs
Examples of bipartite graphs include user–product graphs in recommendation systems, worker–task graphs in assignment problems (the next graphs lesson studies their matchings), trees, grids, hypercubes, and even cycles. Odd cycles are not bipartite: traversing while alternating colors, the last vertex has the same color as the first. That is all that can go wrong.
Proof
If is bipartite and is a cycle, the colors alternate along it: exactly for even . Edge requires , so is odd and is even.
For the converse, handle each component separately. Run BFS from a root and color each vertex by the parity of its layer, . Tree edges and edges to the next layer join different colors. If an edge joins two vertices of the same color, the layer theorem says they must be in the same layer . Let be the first common ancestor of and in the tree. The tree paths from to and from to share only and have the same length , so together with edge they form a cycle of odd length . Therefore, if there are no odd cycles, coloring by layer parity is valid.
∎The proof has a virtue beyond the theorem: both answers come with a certificate. If the graph is bipartite, the 2-coloring proves it, and checking it takes one pass over the edges. If it is not, the odd cycle proves it, and checking it takes one pass over the cycle. The recipient need not trust the algorithm: verifying the certificate suffices. The final coding exercise asks for exactly that, and its tests do not compare against a reference answer: they only verify the certificate.
Euler y Hamilton
The river Pregel ran through Königsberg, around the island of Kneiphof, and split into two branches. Seven bridges connected the city’s four land areas, and the question was whether one could walk across each bridge exactly once. Euler solved the problem in 1736 (Euler, 1741), and his decisive step was abstraction: the shapes of the areas and lengths of the bridges do not matter; only which bridges connect which areas matters. This is a multigraph with four vertices and seven edges.
Necessity. Traverse an Eulerian circuit and consider a vertex . Each time the circuit passes through it enters on one edge and leaves on another, and the first departure from the starting point pairs with the final arrival. The edges incident to are grouped in pairs, so is even. In an open trail, the start and end have one unpaired edge: they are the only odd vertices. In Königsberg the degrees are 3, 3, 5, and 3: four odd vertices, so the walk is impossible. The handshaking corollary explains why there is never just one odd vertex.
Sufficiency: Hierholzer’s algorithm. The classical proof that the condition suffices is an algorithm, published by Carl Hierholzer in 1873 (Euler had established necessity and only sketched sufficiency). Suppose all degrees are even and there is at least one edge.
- Walk until stuck. Start at a vertex and follow unused edges as long as possible. You can only get stuck at : whenever you enter an you have used an odd number of its edges (the pairs of previous steps plus the entry edge), and since is even, an unused edge remains. The trail is a circuit .
- If edges remain, one touches . If an unused edge did not touch , take a path from to (it exists by connectivity) and consider the first edge on the path that is not in : its starting endpoint is in (it is or the endpoint of an edge of ) and the edge is unused. Thus there is a vertex of with unused edges.
- Repeat and splice. Removing the edges of leaves all degrees even, because a circuit uses an even number of edges at each vertex. Walking from produces, by step 1, another circuit that returns to . Inserting into at yields a longer circuit.
Each round uses at least one edge, so the process ends with a circuit using them all. If there are exactly two odd vertices and , add a fictitious edge , take an Eulerian circuit, and remove it: a trail remains from to . With a stack, the three phases merge into one loop costing , which is what you will implement.
The directed version is analogous: a digraph whose arcs lie in one weak component has an Eulerian circuit if and only if at every vertex (each passage through enters on one arc and leaves on another). It has a beautiful application. A de Bruijn sequence of order is a cyclic binary string of length containing every -bit word exactly once as a substring. To construct one, take the words of bits as vertices and add an arc from to for every word . Every vertex has in-degree and out-degree 2 (counting loops at and ), and the digraph is strongly connected, because from any word one can reach any other in steps by adding its bits one at a time. Thus there is an Eulerian circuit, and reading the last bit of each arc produces the sequence. The same idea, with DNA words instead of bits, is at the heart of genome assembly from fragments (Pevzner, Tang and Waterman, 2001).
The contrast with Hamilton
A Hamiltonian cycle passes through every vertex exactly once. Its resemblance to Euler’s problem is superficial and misleading:
| Euler (each edge once) | Hamilton (each vertex once) | |
|---|---|---|
| Characterization | local: degree parity plus connectivity | no simple one is known |
| Algorithm | Hierholzer, | NP-complete (Karp, 1972) |
| Certificate for “no” | an odd-degree vertex, or two edges in different components | no short one is known in general |
There are sufficient conditions, such as Dirac’s (1952): if and every vertex has degree at least , there is a Hamiltonian cycle. But they are only sufficient. The Petersen graph is the classic counterexample: 3-regular, highly symmetric, with no Hamiltonian cycle. The traveling salesperson problem, the weighted version, is the quintessential combinatorial optimization problem, and finding Hamiltonian cycles reminds us that an innocently stated graph question can lie beyond the boundary of tractability.
Implementation from scratch
A minimal graph library using adjacency lists, in pure Python except for matrix algebra. Each piece returns both the answer and the object justifying it, and each cell checks its results against an independent definition on hundreds of random graphs.
from collections import deque
class Graph:
"""Grafo o digrafo sobre los vértices 0..n-1 con listas de adyacencia. Admite aristas paralelas; bucles, solo en el dirigido."""
def __init__(self, n, edges=(), directed=False):
self.n, self.directed = n, directed
self.edges = [] # el índice de cada par es el id de la arista
self.adj = [[] for _ in range(n)] # adj[u] = lista de pares (vecino, id)
for u, v in edges:
self.add_edge(u, v)
def add_edge(self, u, v):
assert self.directed or u != v, "sin bucles en el no dirigido"
eid = len(self.edges)
self.edges.append((u, v))
self.adj[u].append((v, eid))
if not self.directed:
self.adj[v].append((u, eid))
return eid
@property
def m(self):
return len(self.edges)
def neighbors(self, u):
return [v for v, _ in self.adj[u]] # con repeticiones si hay aristas paralelas
def degree(self, u): # en un digrafo, el grado de salida
return len(self.adj[u])
def in_degree(self, v):
return sum(1 for _, w in self.edges if w == v) if self.directed else self.degree(v)
def degree_sequence(self):
return sorted((self.degree(u) for u in range(self.n)), reverse=True)
def reverse(self):
return Graph(self.n, [(v, u) for u, v in self.edges], directed=True)
casa = Graph(5, [(0, 1), (1, 2), (2, 3), (3, 0), (0, 4), (1, 4)])
print("casa: grados", casa.degree_sequence(), " suma =", sum(casa.degree_sequence()), " 2m =", 2 * casa.m)
# Königsberg: A=0 (norte), B=1 (sur), C=2 (isla), D=3 (este); las aristas paralelas son puentes distintos
konigsberg = Graph(4, [(0, 2), (0, 2), (1, 2), (1, 2), (2, 3), (0, 3), (1, 3)])
print("Königsberg: grados", [konigsberg.degree(v) for v in range(4)], " m =", konigsberg.m)
D = Graph(4, [(0, 1), (1, 2), (2, 0), (2, 3)], directed=True)
print("digrafo: salida", [D.degree(v) for v in range(4)], " entrada", [D.in_degree(v) for v in range(4)], " m =", D.m)Each edge stores an identifier. With parallel edges, such as the two bridges between A and C, this is the only way to distinguish “I crossed this bridge” from “I crossed a bridge between A and C,” and it is essential for Hierholzer. Next, the walk theorem is checked against direct enumeration, and reachability is computed using Boolean powers.
import numpy as np
import random
def adjacency_matrix(G):
A = np.zeros((G.n, G.n), dtype=np.int64)
for u, v in G.edges:
A[u, v] += 1
if not G.directed:
A[v, u] += 1
return A
def count_walks_brute(G, i, j, k):
"""Paseos de longitud k de i a j contados uno a uno (coste exponencial: solo para comprobar)."""
if k == 0:
return int(i == j)
return sum(count_walks_brute(G, w, j, k - 1) for w in G.neighbors(i))
rnd = random.Random(1)
for trial in range(40):
n = rnd.randint(2, 6)
directed = trial % 2 == 1
pares = [(u, v) for u in range(n) for v in range(n) if u != v and (directed or u < v)]
G = Graph(n, [e for e in pares for _ in range(rnd.choice([0, 0, 1, 2]))], directed=directed)
A = adjacency_matrix(G)
for k in range(5):
Ak = np.linalg.matrix_power(A, k)
assert all(Ak[i, j] == count_walks_brute(G, i, j, k) for i in range(n) for j in range(n))
print("A^k coincide con la enumeración en 40 multigrafos (20 dirigidos) y k = 0..4")
K4 = Graph(4, [(u, v) for u in range(4) for v in range(u + 1, 4)])
A = adjacency_matrix(K4)
A3 = np.linalg.matrix_power(A, 3)
print("K4: (A^3)_11 =", A3[0, 0], " tr(A^2) =", np.trace(A @ A), "= 2m triángulos = tr(A^3)/6 =", np.trace(A3) // 6)
def reachability(G):
"""R[i, j] = True si j es alcanzable desde i: ((I + A)^(n-1))_ij > 0, por cuadrados sucesivos."""
R = np.minimum(np.eye(G.n, dtype=np.int64) + adjacency_matrix(G), 1)
p = 1
while p < G.n - 1:
R = np.minimum(R @ R, 1) # recortar a 0/1 evita el desbordamiento
p *= 2
return R.astype(bool)
D = Graph(4, [(0, 1), (1, 2), (2, 0), (2, 3)], directed=True)
print("alcanzabilidad en el digrafo:\n", reachability(D).astype(int))Repeated squaring gives with , which suffices because powers greater than add no new reachability. This takes matrix products: it is fast exponentiation applied to transitive closure. The matrix’s last row shows the asymmetry of directed reachability: from 3 only 3 itself is reachable.
Now the two traversals. DFS is iterative, because recursive DFS hits Python’s recursion limit when the graph has a few thousand vertices in a row; the trick is to keep an iterator per vertex on the stack, remembering which edge it had reached when it descended to a child. The checks cover this lesson’s theorems: distances, parentheses, edge classes, the cyclomatic number, and the equivalence between directed cycles and back edges.
def bfs(G, s):
"""Distancias y árbol BFS desde s (None = inalcanzable)."""
dist, parent = [None] * G.n, [None] * G.n
dist[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v, _ in G.adj[u]:
if dist[v] is None: # se marca al encolar, no al sacar
dist[v], parent[v] = dist[u] + 1, u
q.append(v)
return dist, parent
def dfs(G, roots=None):
"""DFS iterativo que imita al recursivo: tiempos d y f con un reloj común, padres y clase de cada arista."""
n = G.n
d, f, parent, pedge = [0] * n, [0] * n, [None] * n, [None] * n
kind, clock = {}, 0
for r in (range(n) if roots is None else roots):
if d[r]:
continue
clock += 1
d[r] = clock
stack = [(r, iter(G.adj[r]))]
while stack:
u, it = stack[-1]
for v, eid in it: # el iterador recuerda por dónde iba
if eid == pedge[u] or eid in kind:
continue # la arista al padre, o una ya vista desde el otro extremo
if not d[v]:
clock += 1
d[v], parent[v], pedge[v] = clock, u, eid
kind[eid] = "tree"
stack.append((v, iter(G.adj[v])))
break # baja a v; u seguirá luego donde lo dejó
elif not f[v]:
kind[eid] = "back" # v sigue en la pila: es antecesor de u
elif d[u] < d[v]:
kind[eid] = "forward"
else:
kind[eid] = "cross"
else: # u agotó sus aristas
clock += 1
f[u] = clock
stack.pop()
return d, f, parent, kind
def n_components(G):
seen, c = [False] * G.n, 0
for s in range(G.n):
if not seen[s]:
c += 1
for v, dv in enumerate(bfs(G, s)[0]):
if dv is not None:
seen[v] = True
return c
rnd = random.Random(7)
for trial in range(300):
n = rnd.randint(1, 9)
directed = trial % 2 == 1
pares = [(u, v) for u in range(n) for v in range(n) if u != v and (directed or u < v)]
G = Graph(n, [e for e in pares if rnd.random() < 0.3], directed=directed)
A = adjacency_matrix(G)
P = [np.linalg.matrix_power(A, k) for k in range(n)]
s = rnd.randrange(n)
dist, _ = bfs(G, s)
for v in range(n): # distancia BFS = menor k con un paseo de longitud k
ks = [k for k in range(n) if P[k][s, v] > 0]
assert dist[v] == (ks[0] if ks else None)
d, f, _, kind = dfs(G)
for u in range(n): # paréntesis: intervalos anidados o disjuntos
for v in range(u + 1, n):
(a0, a1), (b0, b1) = sorted([(d[u], f[u]), (d[v], f[v])])
assert b1 < a1 or a1 < b0
if not directed:
assert all(abs(dist[u] - dist[v]) <= 1 for u, v in G.edges if dist[u] is not None)
assert set(kind.values()) <= {"tree", "back"}
assert list(kind.values()).count("back") == G.m - G.n + n_components(G)
else:
R = reachability(G)
hay_ciclo = any(R[v, u] for u, v in G.edges)
assert hay_ciclo == ("back" in kind.values())
print("300 grafos: distancias BFS, paréntesis, clases de aristas y número de aristas de retroceso correctos")
C7 = Graph(7, [(i, (i + 1) % 7) for i in range(7)])
print("C7 desde 0, distancias:", bfs(C7, 0)[0])
d, f, _, kind = dfs(C7, roots=[0])
print("C7, DFS: d =", d, " f =", f, " retroceso:", [C7.edges[e] for e, k in kind.items() if k == "back"])shows the full contrast. BFS reaches the maximum distance, 3, from both sides, and the edge between vertices 3 and 4, both in layer 3, reveals the odd cycle. DFS goes all the way around, reaching depth 6, and finds a single back edge, the one that closes the cycle: .
Strongly connected components use Kosaraju’s algorithm: a complete DFS computes finishing times, then in the transpose graph the vertices reachable from each vertex are searched in decreasing order. It works because the vertex with greatest is in a source SCC of the condensation graph; in the transpose that SCC is a sink, and the search cannot escape it.
def connected_components(G):
comp, c = [None] * G.n, 0
for s in range(G.n):
if comp[s] is None:
for v, dv in enumerate(bfs(G, s)[0]):
if dv is not None:
comp[v] = c
c += 1
return comp
def kosaraju(G):
"""Componentes fuertemente conexas: DFS completo en G y luego búsquedas en el traspuesto por f decreciente."""
_, f, _, _ = dfs(G)
GT = G.reverse()
comp, c = [None] * G.n, 0
for s in sorted(range(G.n), key=lambda v: -f[v]):
if comp[s] is None:
pila, comp[s] = [s], c
while pila:
u = pila.pop()
for v in GT.neighbors(u):
if comp[v] is None:
comp[v] = c
pila.append(v)
c += 1
return comp
def condensation(G, comp):
arcos = sorted({(comp[u], comp[v]) for u, v in G.edges if comp[u] != comp[v]})
return Graph(max(comp) + 1, arcos, directed=True)
def topological_order(G):
"""Orden topológico: vértices por tiempo de finalización decreciente. None si hay un ciclo."""
_, f, _, kind = dfs(G)
if "back" in kind.values():
return None
return sorted(range(G.n), key=lambda v: -f[v])
S = Graph(7, [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 5), (5, 3), (5, 6)], directed=True)
comp = kosaraju(S)
print("componentes fuertes:", comp, " débiles:", connected_components(Graph(S.n, S.edges)))
H = condensation(S, comp)
print("condensación:", H.edges, " orden topológico:", topological_order(H))
rnd = random.Random(3)
for trial in range(300):
n = rnd.randint(1, 9)
G = Graph(n, [(u, v) for u in range(n) for v in range(n) if u != v and rnd.random() < 0.25], directed=True)
comp = kosaraju(G)
R = reachability(G)
assert all((comp[u] == comp[v]) == bool(R[u, v] and R[v, u]) for u in range(n) for v in range(n))
pos = {c: i for i, c in enumerate(topological_order(condensation(G, comp)))}
assert all(pos[comp[u]] < pos[comp[v]] for u, v in G.edges if comp[u] != comp[v])
print("300 digrafos: CFC = clases de alcanzabilidad mutua, y la condensación siempre tiene orden topológico")The example digraph is weakly connected (one weak component) and has three chained SCCs, : its condensation is a path. The checks compare SCCs against their definition (mutual reachability, computed with the previous cell’s matrix) and verify the condensation theorem on 300 digraphs.
The BFS layer 2-coloring, with both certificate verifiers, follows. Reconstructing the odd cycle from the conflicting edge is the final coding exercise.
def two_color(G):
"""2-coloración por capas BFS. Devuelve (color, None) si es bipartito o (color parcial, arista en conflicto)."""
color = [None] * G.n
for s in range(G.n):
if color[s] is not None:
continue
color[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v, _ in G.adj[u]:
if color[v] is None:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return color, (u, v)
return color, None
def is_proper_2coloring(G, color):
return all(c in (0, 1) for c in color) and all(color[u] != color[v] for u, v in G.edges)
def is_odd_cycle(G, cyc):
aristas = {frozenset(e) for e in G.edges}
k = len(cyc)
return (k >= 3 and k % 2 == 1 and len(set(cyc)) == k
and all(frozenset((cyc[i], cyc[(i + 1) % k])) in aristas for i in range(k)))
ejemplos = {
"C6": Graph(6, [(i, (i + 1) % 6) for i in range(6)]),
"C7": Graph(7, [(i, (i + 1) % 7) for i in range(7)]),
"K3,3": Graph(6, [(i, j) for i in range(3) for j in range(3, 6)]),
"Petersen": Graph(10, [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
+ [(5 + i, 5 + (i + 2) % 5) for i in range(5)]),
}
for nombre, G in ejemplos.items():
color, conflicto = two_color(G)
if conflicto is None:
print(f"{nombre:9s} bipartito, la coloración se verifica: {is_proper_2coloring(G, color)}")
else:
print(f"{nombre:9s} no bipartito: la arista {conflicto} une dos vértices del mismo color")
print("¿es (0 1 2 3 4) un ciclo impar de Petersen?", is_odd_cycle(ejemplos["Petersen"], [0, 1, 2, 3, 4]))Notice that the verifiers are much simpler than the algorithm producing the certificates and do not depend on it. This is the same separation as between a SAT solver and its model checker: complicated code can have errors; the ten-line verifier is easy to audit.
Finally, Hierholzer with a stack. The stack contains the current trail; when its top has no unused edges, the vertex moves to the output. Read backwards, the output is the spliced circuit: each time the algorithm advances again from a vertex on the stack, it opens a subcycle that will eventually be inserted at that point.
def euler_trail(G):
"""Recorrido euleriano (vértices, ids de aristas) o None. Hierholzer con pila: un vértice pasa a la
salida cuando se queda sin aristas libres; la salida, invertida, es el recorrido."""
if G.directed:
if any(G.degree(v) != G.in_degree(v) for v in range(G.n)):
return None # en el dirigido, solo circuitos
start = next((v for v in range(G.n) if G.degree(v)), 0)
else:
odd = [v for v in range(G.n) if G.degree(v) % 2]
if len(odd) not in (0, 2):
return None
start = odd[0] if odd else next((v for v in range(G.n) if G.degree(v)), 0)
used, ptr = [False] * G.m, [0] * G.n
stack, out = [(start, None)], []
while stack:
v, e = stack[-1]
while ptr[v] < len(G.adj[v]) and used[G.adj[v][ptr[v]][1]]:
ptr[v] += 1 # cada entrada de adj se salta una sola vez
if ptr[v] == len(G.adj[v]):
out.append(stack.pop()) # atascado: v pasa a la salida
else:
w, eid = G.adj[v][ptr[v]]
used[eid] = True
stack.append((w, eid))
out.reverse()
if len(out) != G.m + 1:
return None # quedaron aristas en otra componente
return [v for v, _ in out], [e for _, e in out[1:]]
def is_euler_trail(G, verts, eids):
if sorted(eids) != list(range(G.m)):
return False
if G.directed:
return all(G.edges[e] == (verts[i], verts[i + 1]) for i, e in enumerate(eids))
return all(sorted(G.edges[e]) == sorted((verts[i], verts[i + 1])) for i, e in enumerate(eids))
N = "ABCD"
print("Königsberg, 7 puentes:", euler_trail(konigsberg))
k8 = Graph(4, konigsberg.edges + [(0, 1)]) # un octavo puente, A-B
vs, es = euler_trail(k8)
print("con A-B: ", " -> ".join(N[v] for v in vs), " válido:", is_euler_trail(k8, vs, es))
k9 = Graph(4, k8.edges + [(2, 3)]) # y un noveno, C-D
vs, es = euler_trail(k9)
print("con A-B y C-D:", " -> ".join(N[v] for v in vs), " válido:", is_euler_trail(k9, vs, es))
# de Bruijn: cadena cíclica de 2^k bits que contiene cada palabra de k bits exactamente una vez
k = 4
nodos = [format(i, f"0{k - 1}b") for i in range(2 ** (k - 1))]
idx = {s: i for i, s in enumerate(nodos)}
palabras = [format(i, f"0{k}b") for i in range(2 ** k)]
B = Graph(len(nodos), [(idx[w[:-1]], idx[w[1:]]) for w in palabras], directed=True)
vs, es = euler_trail(B)
seq = "".join(palabras[e][-1] for e in es) # cada arco aporta su último bit
ventanas = {(seq + seq[:k - 1])[i:i + k] for i in range(len(seq))}
print(f"de Bruijn B(2, {k}): {seq} longitud {len(seq)}, palabras distintas: {len(ventanas)}")
rnd = random.Random(11)
for trial in range(400):
n = rnd.randint(2, 7)
G = Graph(n, [(u, v) for u in range(n) for v in range(u + 1, n) for _ in range(rnd.choice([0, 0, 1, 2]))])
res = euler_trail(G)
odd = sum(G.degree(v) % 2 for v in range(n))
comps = {c for v, c in enumerate(connected_components(G)) if G.degree(v)}
assert (res is not None) == (len(comps) <= 1 and odd in (0, 2)) # el teorema de Euler, comprobado
if res:
assert is_euler_trail(G, *res)
print("400 multigrafos: hay recorrido euleriano <=> aristas en una sola componente y 0 o 2 vértices impares")With an eighth bridge between A and B, only C and D are odd, and the trail goes from C to D. With a ninth between C and D, all are even and there is a circuit. The de Bruijn sequence of order 4 has 16 bits and contains the 16 four-bit words, each once. The pointer ptr ensures each adjacency-list entry is examined a constant number of times: the algorithm is linear in , unlike the quadratic cost of an implementation that searches for the next unused edge from the start of the list each time.
The library version
networkx implements all of the above with the same semantics, and a few more things:
| Function | What it does | From-scratch equivalent |
|---|---|---|
nx.connected_components(G) | vertex sets of each component | connected_components |
nx.strongly_connected_components(D) | SCCs (iterative Tarjan algorithm) | kosaraju |
nx.condensation(D) | condensation graph, with each node’s SCC in .graph["mapping"] | condensation |
nx.topological_sort(D), nx.all_topological_sorts(D) | one topological order, or all of them | topological_order |
nx.is_bipartite(G), nx.bipartite.color(G) | bipartiteness test and 2-coloring | two_color |
nx.find_cycle(G) | any cycle (not necessarily odd) | back edges of dfs |
nx.is_eulerian(G), nx.eulerian_circuit(G), nx.eulerian_path(G) | Euler, with multigraphs | euler_trail |
nx.is_isomorphic(G, H) | exact isomorphism (VF2) | isomorfismos |
nx.could_be_isomorphic, nx.faster_could_be_isomorphic | invariant filters: False disproves, True proves nothing | invariantes |
import networkx as nx
import warnings
warnings.filterwarnings("ignore") # networkx avisa de que los hashes WL cambiaron en la versión 3.5
def to_nx(G):
H = nx.MultiDiGraph() if G.directed else nx.MultiGraph()
H.add_nodes_from(range(G.n))
H.add_edges_from(G.edges)
return H
S_nx = nx.DiGraph(S.edges)
print("CFC:", sorted(map(sorted, nx.strongly_connected_components(S_nx))), " desde cero:", kosaraju(S))
C = nx.condensation(S_nx)
print("condensación:", sorted(C.edges), " es DAG:", nx.is_directed_acyclic_graph(C))
for nombre, G in ejemplos.items():
print(f"{nombre:9s} is_bipartite: {nx.is_bipartite(nx.Graph(G.edges))} desde cero: {two_color(G)[1] is None}")
print("\nKönigsberg es euleriano:", nx.is_eulerian(to_nx(konigsberg)), " con A-B tiene recorrido:", nx.has_eulerian_path(to_nx(k8)))
print("circuito con A-B y C-D:", " ".join(N[u] + N[v] for u, v, _ in nx.eulerian_circuit(to_nx(k9), source=0, keys=True)))
pares = {
"K3,3 / prisma": (nx.complete_bipartite_graph(3, 3), nx.circular_ladder_graph(3)),
"C6 / 2 K3": (nx.cycle_graph(6), nx.disjoint_union(nx.complete_graph(3), nx.complete_graph(3))),
"estrella / C4 + K1": (nx.star_graph(4), nx.disjoint_union(nx.cycle_graph(4), nx.empty_graph(1))),
}
print(f"\n{'par':20s} {'faster_could':>13s} {'could_be':>9s} {'mismo WL':>9s} {'isomorfos':>10s}")
for nombre, (G1, G2) in pares.items():
wl = nx.weisfeiler_lehman_graph_hash(G1) == nx.weisfeiler_lehman_graph_hash(G2)
print(f"{nombre:20s} {str(nx.faster_could_be_isomorphic(G1, G2)):>13s} {str(nx.could_be_isomorphic(G1, G2)):>9s}"
f" {str(wl):>9s} {str(nx.is_isomorphic(G1, G2)):>10s}")Three details of the output. networkx numbers condensation components in a different order (so its arcs appear reversed relative to ours): the structure is the same, a path of three SCCs. faster_could_be_isomorphic only looks at the degree sequence and distinguishes neither from the prism nor from two triangles, while could_be_isomorphic adds the number of triangles and cliques at each vertex and distinguishes them. The Weisfeiler–Leman hash, the basis of graph kernels and the expressivity limit of message-passing networks, distinguishes neither of the first two pairs: all their vertices have the same degree, and color refinement does not advance even one round.
Common mistakes
Exercises
Step 1 of 3. What is when counted by edges?
More than one answer may be correct.
Step 1 of 4. What coloring do you propose?
odd_cycle_or_bipartition(n, edges) for a simple undirected graph with vertices 0..n-1. It must return ('bipartition', color), with color[v] equal to 0 or 1 and different colors at each edge's endpoints, or ('odd_cycle', ciclo), with ciclo = [v0, ..., vk-1] of odd length, no repeated vertices, and all consecutive edges (including the closing one) present. The graph may be disconnected. The tests do not compare against an answer: they only verify the certificate.from collections import deque
def odd_cycle_or_bipartition(n, edges):
"""Devuelve ("bipartition", color) o ("odd_cycle", ciclo)."""
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# tu código: BFS por componentes guardando color y padre;
# ante una arista entre colores iguales, reconstruye el ciclo por el primer antecesor común
return "bipartition", [0] * nStep 1 of 3. Which object do you choose?
Summary
- Degrees and edges are tied by handshaking, , so the number of odd vertices is even. The three representations (matrix, lists, incidence) have different costs, and the matrix opens the door to linear algebra: counts walks, not paths; counts triangles.
- Isomorphism is disproved by a differing invariant (degrees, triangles, spectrum, bipartiteness) and proved by a bijection. No cheap invariant is complete: cospectral graphs exist, and regular graphs of the same degree fool Weisfeiler–Leman and message-passing networks.
- Connectivity is an equivalence relation. In digraphs distinguish weak from strong connectivity; the contracted SCCs form a DAG, the condensation graph.
- A digraph is acyclic if and only if it admits a topological order, and reachability in a DAG is a partial order whose linear extensions are its topological orders.
- BFS constructs a distance tree: its non-tree edges join equal or consecutive layers. DFS constructs a tree with parenthesis structure: in undirected graphs every non-tree edge is a back edge (there are ), and in directed graphs a cycle exists if and only if a back edge exists.
- A graph is bipartite if and only if it has no odd cycles; BFS produces the 2-coloring or an odd cycle. A connected multigraph is Eulerian if and only if all degrees are even, and Hierholzer builds the circuit by splicing cycles in linear time. Hamilton, by contrast, is NP-complete.