Module contents
Lesson 14 of 22Core 110 min

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, C4H10\mathrm{C_4H_{10}}, 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 E⊆V×VE \subseteq V \times V on a finite set, drawn with points and arrows; an undirected graph is a symmetric, irreflexive relation with one line per pair {u,v}\{u, v\}. Almost every question starts with counting. Draw some graphs and see what changes and what does not.

InteractiveGraph sandbox
Quitar la arista 1-2Quitar la arista 2-3Quitar la arista 3-4Quitar la arista 4-1Quitar la arista 1-3Quitar la arista 5-6Quitar la arista 6-7121234567
  • vertex color: its connected component
  • selected walk (numbers give step order)
Matrix A2\mat{A}^{2}: entry (i,j)(i, j) counts walks of length 2
12345671234567
(A2)13=2(\mat{A}^{2})_{13} = 2: 2 walks from 1 to 3
∑vdeg⁡v=2m\textstyle\sum_v \deg v = 2m always holds, so the number of odd-degree vertices is even.
2
Vertices and edgesn = 7, m = 7
Degree sequence(3,3,2,2,2,1,1)
Degree sum14 = 2 · 7
Odd-degree vertices4
Connected components2
Triangles, tr⁡(A3)/6\tr(\mat{A}^3)/612 / 6 = 2
Click the background to add vertices and two vertices in succession to join them; click an edge to remove it. On the right are the degree sequence and its sum: compare it with 2m2m for any graph you draw. Colors mark connected components, or strongly connected components if you enable 'Directed'. Below is the matrix Ak\mat{A}^k: hover over an entry to see the walks it counts, with one drawn and its steps numbered. In K4K_4 with k=3k = 3, how many closed walks start at each vertex, and how many repeat vertices? Choose the digraph and find a nonzero (i,j)(i, j) entry with zero (j,i)(j, i): what does it say about reachability?

Three observations proved in the rest of the lesson:

  1. 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.
  2. Entry (i,j)(i, j) of Ak\mat{A}^k counts walks from ii to jj with exactly kk steps, including those that go back and forth along the same edge. That is why the counts grow so quickly: they are not paths.
  3. 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 uv∈Euv \in E, vertices uu and vv are adjacent or neighbors, and the edge is incident to both. The neighborhood of vv is N(v)={u:uv∈E}N(v) = \{u : uv \in E\}, and its degree is its number of incident edges, deg⁡v\deg v: in a simple graph this is ∣N(v)∣\abs{N(v)}, while a multigraph counts each parallel edge separately. In a digraph distinguish out-degree d+(v)d^+(v) (arcs with tail vv) from in-degree d−(v)d^-(v). The degree sequence lists degrees from largest to smallest.

A few families appear repeatedly and are worth keeping handy:

FamilyVerticesEdgesDegrees
complete KnK_nnn(n2)\binom{n}{2}all n−1n - 1
cycle CnC_n (n≥3n \ge 3)nnnnall 2
path PnP_nnnn−1n - 1two of degree 1, the rest 2
complete bipartite Kp,qK_{p,q}p+qp + qpqpqqq on one side, pp on the other
hypercube QdQ_d2d2^d (dd-bit words)d 2d−1d\,2^{d-1}all dd (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 GG is a graph H=(V′,E′)H = (V', E') with V′⊆VV' \subseteq V and E′⊆EE' \subseteq E. It is induced by V′V', written G[V′]G[V'], if it contains all edges of GG with both endpoints in V′V'; it is spanning if V′=VV' = V. The complement Gˉ\bar G has the same vertices and exactly the edges missing from GG. The distinction matters: C4C_4 is a subgraph of K4K_4, but no induced subgraph of K4K_4 is an C4C_4.

Representations and what they count

The choice is an engineering tradeoff. The matrix occupies n2n^2 entries even with few edges and answers “is uvuv an edge?” in constant time; lists use space proportional to n+mn + m and traverse neighbors of vv in time proportional to deg⁡v\deg v. Real graphs are nearly always sparse (m≪n2m \ll n^2: a social network with 10910^9 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 (u→v→uu \to v \to u) are valid.

Proof

Use induction on kk. For k=0k = 0, A0=I\mat{A}^0 = \mat{I} and the only length-0 walk stays put, from ii to ii. Assume the claim for kk. Every walk of length k+1k + 1 from ii to jj decomposes uniquely into a walk of length kk from ii to some ll, followed by an edge from ll to jj. For fixed ll there are (Ak)il(\mat{A}^k)_{il} choices for the first part and alja_{lj} for the edge. Summing over ll by the sum rule gives

#{paseos de longitud k+1 de i a j}=∑l=1n(Ak)il alj=(AkA)ij=(Ak+1)ij,\#\{\text{paseos de longitud } k + 1 \text{ de } i \text{ a } j\} = \sum_{l=1}^n (\mat{A}^k)_{il}\, a_{lj} = (\mat{A}^{k}\mat{A})_{ij} = (\mat{A}^{k+1})_{ij},

which is the definition of matrix multiplication.

∎

The theorem turns combinatorial questions into matrix calculations. For a simple undirected graph:

  • (A2)ii=deg⁡i(\mat{A}^2)_{ii} = \deg i: a closed walk of length 2 goes to a neighbor and back. Thus tr⁡(A2)=∑ideg⁡i=2m\tr(\mat{A}^2) = \sum_i \deg i = 2m, the handshaking lemma again.
  • tr⁡(A3)=6 t\tr(\mat{A}^3) = 6\,t, where tt 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.
  • (A2)ij(\mat{A}^2)_{ij} with i≠ji \neq j counts common neighbors of ii and jj, the basis of many recommendation heuristics (“friends of friends”).

Another consequence: jj is reachable from ii if and only if there is a walk from ii to jj, and, as we will soon see, if there is one, there is one of length at most n−1n - 1. Thus, jj is reachable from ii if and only if ((I+A)n−1)ij>0\big((\mat{I} + \mat{A})^{n-1}\big)_{ij} > 0. 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 C4C_4 to K4K_4, which are not isomorphic.

Deciding isomorphism by trying the n!n! bijections becomes infeasible from n≈12n \approx 12 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 φ\varphi maps the neighborhood of vv bijectively to that of φ(v)\varphi(v), 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 AH=PAGP⊤\mat{A}_H = \mat{P}\mat{A}_G\mat{P}\T with P\mat{P} a permutation matrix, then P⊤=P−1\mat{P}\T = \mat{P}\inv and AH\mat{A}_H is similar to AG\mat{A}_G: 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:

PairAgree onDistinguished by
K3,3K_{3,3} and the triangular prismn=6n = 6, m=9m = 9, all degrees 3, connectedtriangles: 0 versus 2; bipartiteness; spectrum
C6C_6 and two disjoint trianglesn=6n = 6, m=6m = 6, all degrees 2connectedness; triangles; spectrum
star K1,4K_{1,4} and C4C_4 plus an isolated vertexspectrum: 2,0,0,0,−22, 0, 0, 0, -2degree 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.

[ ]Invariants and searching for isomorphismsBrowser
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: K3,3K_{3,3} has 72=2⋅3!⋅3!72 = 2 \cdot 3! \cdot 3! (permuting each side and swapping them), the prism and C6C_6 have 12, and the Petersen graph has 120. Pruning by degree and consistency makes the search explore a tiny fraction of Petersen’s 10!≈3.6×10610! \approx 3.6 \times 10^6 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 uu to vv formed from edges of the given walk there is one of minimum length, u=v0,…,vk=vu = v_0, \dots, v_k = v. If it repeated a vertex, vi=vjv_i = v_j with i<ji < j, the walk v0,…,vi,vj+1,…,vkv_0, \dots, v_i, v_{j+1}, \dots, v_k would be shorter and of the same kind. Therefore its vertices are distinct: it is a path. Since it has k+1k + 1 distinct vertices, k≤n−1k \le n - 1.

∎

In a connected undirected graph, dd is a distance in the metric sense: it is symmetric, vanishes only at u=vu = v, and satisfies the triangle inequality, because concatenating a path from uu to ww and another from ww to vv gives a walk from uu to vv. In a digraph, d(u,v)d(u, v) and d(v,u)d(v, u) can differ (and one can be infinite).

Proof

Use induction on mm, removing and replacing an edge. Without edges, each vertex is its own component: c=nc = n. Adding an edge uvuv to a graph leaves the components unchanged if uu and vv were already in the same one; otherwise it merges exactly two into one. In both cases cc falls by at most 1 when mm increases by 1, so c+m≥nc + m \ge n is preserved.

∎

Equality c=n−mc = n - m 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 1→2→3→11 \to 2 \to 3 \to 1, 3→43 \to 4 is weakly connected, but no edge leaves 4: it has two SCCs, {1,2,3}\{1, 2, 3\} and {4}\{4\}. Contracting each SCC to a point leaves a very specific structure.

Proof

If there were a cycle Ci1→Ci2→⋯→Cik→Ci1C_{i_1} \to C_{i_2} \to \cdots \to C_{i_k} \to C_{i_1} with k≥2k \ge 2, each vertex of Ci1C_{i_1} could reach every vertex of Ci2C_{i_2} (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 Ci1C_{i_1} and Ci2C_{i_2} 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 w0w_0 there is an arc w1→w0w_1 \to w_0, from w1w_1 another w2→w1w_2 \to w_1, and so on. Among w0,…,wnw_0, \dots, w_n there are n+1n + 1 vertices, so by the pigeonhole principle one repeats, wi=wjw_i = w_j with i<ji < j, and wj→⋯→wiw_j \to \cdots \to w_i 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 u0→u1→⋯→u0u_0 \to u_1 \to \cdots \to u_0, the positions of the uiu_i would strictly increase around the cycle and return to the starting position: impossible. Conversely, use induction on nn: a DAG with n≥1n \ge 1 vertices has a source ss; removing it leaves a DAG, which by the induction hypothesis has a topological order; placing ss at the front gives one for the whole graph, because no arc enters ss.

∎

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 DD, define u⪯vu \preceq v if vv is reachable from uu.

Proof

⪯\preceq is reflexive and transitive by construction (walks of length 0 and concatenation). It is antisymmetric: if u⪯vu \preceq v and v⪯uv \preceq u with u≠vu \neq v, concatenating the two walks yields a closed directed walk of positive length, which contains a cycle. A total order on VV extends ⪯\preceq if and only if it respects every arc, because the arcs generate ⪯\preceq by transitivity; that is the definition of a topological order, so the linear extensions of ⪯\preceq are the topological orders. Conversely, the Hasse diagram of a finite order has an arc x→yx \to y when yy covers xx; it is acyclic because its arcs strictly increase in the order, and in a finite order every relation x<yx < y decomposes into a chain of cover relations.

∎

Different DAGs can have the same reachability: adding the arc u→wu \to w when u→v→wu \to v \to w 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 ss. 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 uu from the frontier, examine its edges uvuv, and whenever vv is new, discover it, record its parent uu, and add it to the frontier.

Counting shows that the result is a tree: every discovered vertex other than ss contributes exactly one edge (its parent’s), and the parent was discovered before the child, so following parents from any vertex ends at ss without repetition. In an undirected graph it is a spanning tree of the component of ss; in a digraph, it is a tree whose arcs point away from the root and cover what is reachable from ss.

InteractiveBFS and DFS trees side by side
step 27 / 27
BFS: queue (first in, first out)
1d=02d=13d=24d=35d=16d=27d=38d=49d=210d=3
Queue:empty
Queue empty: finished. Each reached vertex is at the level of its distance from the root.
DFS: stack (last in, first out)
11/2022/1933/1844/1758/1367/1476/1585/1699/121010/11
Stack:empty
Stack empty: finished.
  • BFS tree
  • BFS: same level
  • BFS: next level
  • DFS tree
  • DFS: back edge
Next to each vertex: dd = distance (BFS) and discovery/finish (DFS).
BFS levels (0, 1, 2...)1 | 2,5 | 3,6,9 | 4,7,10 | 8
Tree height: BFS · DFS4 · 9
BFS non-tree: same level · next2 · 4
DFS: back = m − n + 16 = 15 − 10 + 1
Both traversals advance from the same root: at each step BFS removes a vertex from the queue or examines an edge, and DFS examines an edge, descends to a new vertex, or finishes one. BFS records each vertex's distance dd; DFS records its discovery and finishing times. Thick edges belong to the tree; dashed edges do not. Notice that BFS edges always join the same layer or consecutive layers, and that each DFS back edge closes a cycle, shaded when it appears. At the end, enable ‘Draw as tree’ (Dibujar como árbol): BFS is wide and shallow, DFS narrow and deep. For the cycle of 7, which BFS edge joins two vertices in the same layer? The digraph shows all four DFS edge types.

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 ss) and is preserved because the first vertex, at layer LL, is removed and vertices at layer L+1L + 1 are added at the end. Thus vertices leave the queue in nondecreasing layer order.

Now ℓ(v)≥d(s,v)\ell(v) \ge d(s, v) because the tree path from ss to vv has length ℓ(v)\ell(v). For the other inequality, use strong induction on k=d(s,v)k = d(s, v). If k=0k = 0, v=sv = s. If k≥1k \ge 1, let ww be the penultimate vertex of a shortest path from ss to vv; d(s,w)=k−1d(s, w) = k - 1 and by hypothesis ℓ(w)=k−1\ell(w) = k - 1. When ww leaves the queue and examines edge wvwv, either vv is new and receives ℓ(v)=k\ell(v) = k, or it was already discovered by a vertex uu that left before ww, with ℓ(u)≤ℓ(w)\ell(u) \le \ell(w), and then ℓ(v)=ℓ(u)+1≤k\ell(v) = \ell(u) + 1 \le k.

The edge claim follows from the triangle inequality: if uv∈Euv \in E, d(s,v)≤d(s,u)+1d(s, v) \le d(s, u) + 1, 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 uvuv joins two vertices in the same layer LL, the tree branches from uu and vv to their first common ancestor zz have the same length L−ℓ(z)L - \ell(z) and, together with uvuv, form a cycle of odd length 2(L−ℓ(z))+12(L - \ell(z)) + 1. 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 (d[v]d[v]) and when it is finished (f[v]f[v], when it has no edges left to examine). While vv is on the stack, between d[v]d[v] and f[v]f[v], it is called gray; before that, white; afterward, black.

Proof

The stack never reorders: if vv is pushed while uu is on it, vv is above uu (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 uu to vv is white at d[u]d[u]. For the converse, suppose some vertex on the white path u=w0,…,wk=vu = w_0, \dots, w_k = v does not become a descendant and let wiw_i be the first. Then wi−1w_{i-1} is a descendant of uu (or is uu) and f[wi−1]≤f[u]f[w_{i-1}] \le f[u]; since wi−1w_{i-1} examines the edge to wiw_i before finishing, wiw_i is discovered before f[wi−1]f[w_{i-1}] and after d[u]d[u] because it was white at that time. Thus d[u]<d[wi]<f[u]d[u] < d[w_i] < f[u], and by the parenthesis structure the interval of wiw_i lies inside that of uu: 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 uu to vv that is not in the tree is a back edge if vv is an ancestor of uu (it is gray), a forward edge if it is an already finished descendant, and a cross edge if vv is in another, already finished branch.

Proof

(a) Let uvuv be an edge and suppose d[u]<d[v]d[u] < d[v]. At d[u]d[u], vv is white and u,vu, v is a white path, so vv is a descendant of uu: the edge joins ancestor and descendant. DFS forests have n−cn - c edges (each component contributes a tree with one more vertex than edges), and all other edges are back edges. Each back edge uvuv, together with the tree path from vv to uu, forms a cycle; and if there are none, the graph is its DFS forest.

(b) A back edge u→vu \to v and the tree path from vv to uu form a cycle. Conversely, let CC be a cycle, vv its first discovered vertex, and u→vu \to v the arc of CC entering vv. At d[v]d[v], the rest of CC is a white path from vv to uu, so uu is a descendant of vv and, when uu examines u→vu \to v, vv is still gray: it is a back edge. For the order: if there are no back edges, when an arc u→vu \to v is examined, vv is white (and will be a descendant, with f[v]<f[u]f[v] < f[u]) or black (also with f[v]<f[u]f[v] < f[u]). Every arc goes from greater to smaller ff.

∎

The number m−n+cm - n + c 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, O(n+m)O(n + m) 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 C2k+1C_{2k+1} while alternating colors, the last vertex has the same color as the first. That is all that can go wrong.

Proof

If GG is bipartite and v0,v1,…,vk−1,v0v_0, v_1, \dots, v_{k-1}, v_0 is a cycle, the colors alternate along it: c(vi)=c(v0)c(v_i) = c(v_0) exactly for even ii. Edge vk−1v0v_{k-1}v_0 requires c(vk−1)≠c(v0)c(v_{k-1}) \neq c(v_0), so k−1k - 1 is odd and kk is even.

For the converse, handle each component separately. Run BFS from a root ss and color each vertex by the parity of its layer, c(v)=ℓ(v) mod 2c(v) = \ell(v) \bmod 2. Tree edges and edges to the next layer join different colors. If an edge uvuv joins two vertices of the same color, the layer theorem says they must be in the same layer LL. Let zz be the first common ancestor of uu and vv in the tree. The tree paths from zz to uu and from zz to vv share only zz and have the same length L−ℓ(z)≥1L - \ell(z) \ge 1, so together with edge uvuv they form a cycle of odd length 2(L−ℓ(z))+12(L - \ell(z)) + 1. 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.

InteractiveTwo colors or an odd cycle
step 21 / 21
1234root5678910
Odd cycle of length 5 = 2 + 2 + 1. This certifies that there is no 2-coloring.
  • color A
  • color B
  • BFS tree edge
  • paths to the common ancestor
  • conflicting edge and odd cycle
Colored vertices10 / 10
Edges checked10 / 12
Cycle length5 (odd)
Not bipartite. Certificate: cycle 3-2-1-9-8-3. Check: its edges exist, distinct vertices, odd length 5 ✓.
BFS colors by layers, alternating A and B, and checks each edge it examines. Play the ladder with a shortcut: the shortcut creates an odd cycle, and when an edge joins two vertices of the same color, the algorithm climbs the tree from its endpoints to their first common ancestor; the two branches and the edge form the cycle, shown in red with its verification. Enable ‘Arrange by BFS layers’ (Disponer por capas BFS): the conflicting edge is always horizontal, within one layer. Then break the cycle by removing an edge (click its two endpoints) and watch the certificate become a coloring. Try Petersen from different roots: does the cycle found change? Does its length change?

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 vv. Each time the circuit passes through vv 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 vv are grouped in pairs, so deg⁡v\deg v 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.

  1. Walk until stuck. Start at a vertex vv and follow unused edges as long as possible. You can only get stuck at vv: whenever you enter an w≠vw \neq v you have used an odd number of its edges (the pairs of previous steps plus the entry edge), and since deg⁡w\deg w is even, an unused edge remains. The trail is a circuit CC.
  2. If edges remain, one touches CC. If an unused edge xyxy did not touch CC, take a path from vv to xx (it exists by connectivity) and consider the first edge on the path that is not in CC: its starting endpoint is in CC (it is vv or the endpoint of an edge of CC) and the edge is unused. Thus there is a vertex uu of CC with unused edges.
  3. Repeat and splice. Removing the edges of CC leaves all degrees even, because a circuit uses an even number of edges at each vertex. Walking from uu produces, by step 1, another circuit C′C' that returns to uu. Inserting C′C' into CC at uu 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 aa and bb, add a fictitious edge abab, take an Eulerian circuit, and remove it: a trail remains from aa to bb. With a stack, the three phases merge into one loop costing O(m)O(m), which is what you will implement.

InteractiveEditable bridges of Königsberg
Adegree 3 · oddBdegree 3 · oddCdegree 5 · oddDdegree 3 · oddPregel river++++++
Adegree 3Bdegree 3Cdegree 5Ddegree 3
Hierholzer’s algorithm activates when there are 0 or 2 odd areas and the bridges form a connected whole.
  • bridge not yet crossed
  • first walk
  • cycles spliced later
  • odd degree
A (north bank) · B (south bank) · C (Kneiphof island) · D (eastern area)
Degrees (A, B, C, D)3, 3, 5, 3
Odd-degree areas4: A, B, C, D
Bridges7
4 areas have odd degree (A, B, C, D): impossible. Each intermediate visit uses two bridges, so only the start and end can be odd.
The seven bridges of 1736 on a schematic map and, on the right, Euler's multigraph: one vertex per area, one edge per bridge. Odd areas appear in red. Remove or add bridges by clicking them (gaps marked + are new bridges) until 0 or 2 odd areas remain, and play Hierholzer: the first trail starts and gets stuck, and a new cycle in another color starts at a point on the trail with unused bridges and is spliced in. At the end, each bridge is numbered in traversal order. What is the minimum number of new bridges needed for a circuit returning to the start? What happens if you remove a bridge instead of adding one?

The directed version is analogous: a digraph whose arcs lie in one weak component has an Eulerian circuit if and only if d+(v)=d−(v)d^+(v) = d^-(v) at every vertex (each passage through vv enters on one arc and leaves on another). It has a beautiful application. A de Bruijn sequence of order kk is a cyclic binary string of length 2k2^k containing every kk-bit word exactly once as a substring. To construct one, take the 2k−12^{k-1} words of k−1k - 1 bits as vertices and add an arc from x1⋯xk−1x_1 \cdots x_{k-1} to x2⋯xkx_2 \cdots x_k for every word x1⋯xkx_1 \cdots x_k. Every vertex has in-degree and out-degree 2 (counting loops at 0⋯00 \cdots 0 and 1⋯11 \cdots 1), and the digraph is strongly connected, because from any word one can reach any other y1⋯yk−1y_1 \cdots y_{k-1} in k−1k - 1 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)
Characterizationlocal: degree parity plus connectivityno simple one is known
AlgorithmHierholzer, O(m)O(m)NP-complete (Karp, 1972)
Certificate for “no”an odd-degree vertex, or two edges in different componentsno short one is known in general

There are sufficient conditions, such as Dirac’s (1952): if n≥3n \ge 3 and every vertex has degree at least n/2n/2, 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.

[ ]The Graph class and the handshaking lemmaBrowser
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.

[ ]Walks using powers of ABrowser
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 (I+A)2r(\mat{I} + \mat{A})^{2^r} with 2r≥n−12^r \ge n - 1, which suffices because powers greater than n−1n - 1 add no new reachability. This takes O(log⁡n)O(\log n) 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.

[ ]BFS and DFS with their theorems checkedBrowser
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"])

C7C_7 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: m−n+c=7−7+1m - n + c = 7 - 7 + 1.

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 ff order. It works because the vertex with greatest ff is in a source SCC of the condensation graph; in the transpose that SCC is a sink, and the search cannot escape it.

[ ]Components, condensation, and topological orderBrowser
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, {0,1,2}→{3,4,5}→{6}\{0, 1, 2\} \to \{3, 4, 5\} \to \{6\}: 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.

[ ]Bipartition and certificate verifiersBrowser
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.

[ ]Hierholzer, de Bruijn, and Euler's theorem checkedBrowser
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 mm, 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:

FunctionWhat it doesFrom-scratch equivalent
nx.connected_components(G)vertex sets of each componentconnected_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 themtopological_order
nx.is_bipartite(G), nx.bipartite.color(G)bipartiteness test and 2-coloringtwo_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 multigraphseuler_trail
nx.is_isomorphic(G, H)exact isomorphism (VF2)isomorfismos
nx.could_be_isomorphic, nx.faster_could_be_isomorphicinvariant filters: False disproves, True proves nothinginvariantes
[ ]networkx versus the custom libraryBrowser
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 K3,3K_{3,3} from the prism nor C6C_6 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

ProofThe handshaking lemma
Prove: In every multigraph, ∑v∈Vdeg⁡v=2m\sum_{v \in V} \deg v = 2m, and the number of odd-degree vertices is even.
0
Let G=(V,E)G = (V, E) be a loopless multigraph and let S={(v,e)∈V×E:v es extremo de e}S = \{(v, e) \in V \times E : v \text{ es extremo de } e\} be the set of incidences.

Step 1 of 3. What is ∣S∣\abs{S} when counted by edges?

NumericClosed walks in K4
How many closed walks of length 3 start at a fixed vertex of K4K_4 and return to it?
NumericWalks are not cycles
How many closed walks of length 4 leave a fixed vertex of cycle C4C_4 and return to it?
QuizSame degree sequence
K3,3K_{3,3} and the triangular prism (two triangles with corresponding vertices joined) have 6 vertices, 9 edges, and all degrees equal to 3. Which invariants prove they are not isomorphic?

More than one answer may be correct.

NumericStrong components
How many strongly connected components does the digraph with vertices 1,…,71, \dots, 7 and arcs 1→21 \to 2, 2→32 \to 3, 3→13 \to 1, 3→43 \to 4, 4→54 \to 5, 5→65 \to 6, 6→46 \to 4, 6→76 \to 7 have?
NumericHow many topological orders?
A DAG has vertices 1,…,51, \dots, 5 and arcs 1→21 \to 2, 1→31 \to 3, 2→42 \to 4, 3→43 \to 4; vertex 5 has no arcs. How many topological orders does it admit?
QuizA DFS that is not DFS
A colleague writes: ‘pop uu from the stack; for each unmarked neighbor vv of uu, mark it, set padre(v)=u\mathrm{padre}(v) = u and push it.’ In a connected undirected graph, which guarantee of real DFS is lost?
NumericNew bridges for Königsberg
In 1736 Königsberg (degrees 3, 3, 5, and 3), what is the minimum number of new bridges needed for an Eulerian circuit, a walk crossing each bridge once and returning to the start?
ProofNo odd cycles implies bipartite
Prove: If a graph contains no odd-length cycle, it is bipartite.
0
Let GG be a graph with no odd cycles. It suffices to construct a 2-coloring of each connected component; fix a component and a vertex rr in it. This proof uses only distances and walks, not the BFS tree.

Step 1 of 4. What coloring do you propose?

CodeBipartition or odd cycle, with certificate
Implement 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] * n
Shift+Enter to run
ProofEven degrees, Eulerian circuit
Prove: If a connected multigraph with at least one edge has all degrees even, it has an Eulerian circuit.
0
A proof different from Hierholzer's, using extremality. Let GG be connected, with m≥1m \ge 1 and all degrees even.

Step 1 of 3. Which object do you choose?

Summary

Key idea
A graph is a relation that can be drawn, and nearly every question asked about it (how many walks, whether two are the same, what is reachable, whether it can be ordered, colored, or traversed) has an answer that comes with a certificate: a small object anyone can check.
  • Degrees and edges are tied by handshaking, ∑vdeg⁡v=2m\sum_v \deg v = 2m, 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: (Ak)ij(\mat{A}^k)_{ij} counts walks, not paths; tr⁡(A3)=6⋅\tr(\mat{A}^3) = 6 \cdot 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 m−n+cm - n + c), 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.