Depth-first search, topological sort and components
Build linear graph traversals, topological orders, strongly connected components, bridges and articulation points, with proofs and practical representations.
After this lesson you can
- Choose graph representations based on density and required operations, including CSR.
- Prove the parenthesis theorem and classify DFS edges.
- Implement Kahn and DFS topological sorting and detect cycles with a certificate.
- Implement iterative Tarjan strongly connected components and build the condensation graph.
- Detect bridges and articulation points using low values.
Before you start
Motivation: ordering dependencies
A build system receives four hundred modules and a list of who imports whom. Before compiling a module, everything it imports must already be compiled. The first question is whether an order respects that; the second is which order; and if none exists, the useful message is not merely “there is a cycle” but “these three modules import each other in a circle, and this import closes it”. All three questions can be answered in linear time with the same tool: depth-first search recording when each vertex is discovered and finished.
That structure appears in very different places:
- Software builds.
make,cargoor a package manager’s dependency resolver orders a dependency graph. Cycles are Python’sImportError: cannot import name ... (most likely due to a circular import). - Autograd. A network’s computational graph is acyclic: the backward pass (backpropagation) can compute a node’s gradient only after all consumers have contributed theirs, traversing nodes in reverse topological order.
- Mutual recursion. In a program’s call graph, cycles are functions calling each other. A compiler or static analyzer groups definitions into strongly connected components and processes each group after everything it depends on. Haskell uses this for type inference (the Haskell Report calls it dependency analysis).
- Logic. Deciding a formula with two-literal clauses (2-SAT) reduces to strongly connected components of an implication graph, as proved below.
- Networks. Which link or node, if removed, splits a network in two: bridges and articulation points.
The lesson follows that order: first graph storage and operation costs, then depth-first search and its theory (the parenthesis and white-path theorems), and on that foundation topological order, strongly connected components with Kosaraju and Tarjan, and bridges. Basic graph vocabulary (definitions, paths and connectivity, directed acyclic graphs) is assumed from discrete mathematics; algorithms and analysis are new here. We use with vertices numbered , and edges; the graph is directed unless stated otherwise.
Graph representations and their costs
Mathematics does not distinguish ways of storing a graph; algorithms do. What matters is which operations are needed and how often.
Three representations cover almost everything:
- Adjacency matrix. with if . It occupies cells even with few edges.
- Adjacency lists. For each , a list of outgoing neighbors. Occupies .
- CSR (compressed sparse row, the
scipy.sparseformat). All lists concatenated in one arrayindicesof length , plus arrayindptrof length such that neighbors of areindices[indptr[u]:indptr[u+1]]. Slice length is the out-degree of .
| Representation | Memory | Neighbors of | Is ? | Add edge |
|---|---|---|---|---|
| Matrix | ||||
| Adjacency lists | amortized (with a dynamic array) | |||
| Lists with sets | , large constant | expected | expected | |
| CSR | , compact | , contiguous | if row sorted | : rebuild |
CSR gives up modifications for compactness and locality: a vertex’s neighbors are consecutive in memory and traversal is a sequential read the processor can prefetch; Python’s list of lists follows pointers to scattered objects. The RAM model misses this difference (it counts reads, not cache misses), but in practice it matters as much as any constant. An undirected graph stores each edge twice, once per direction; a weighted graph adds array data parallel to indices, exactly what scipy.sparse.csr_matrix stores.
Building CSR from an edge list costs with counting sort by source: count degrees, a prefix sum gives indptr, and one pass places each edge. The figure shows what each structure reads for two operations.
Memory matters too. A byte matrix for vertices occupies a terabyte even with only 16 neighbors per vertex; the same graph’s CSR uses 68 MB. The bit matrix ( bytes) beats CSR with 32-bit indices, bytes, when , that is, when exceeds approximately : average degree . For millions of vertices this never happens; for a thousand vertices and degree 32 it already does.
The Python-list model counts per edge an 8-byte pointer inside the list and a 28-byte int object (integers above 256 are not shared), and per vertex a list header. This is a model, not a measurement: below we measure a real graph, and in 32-bit Pyodide absolute figures are smaller. The expected conclusion holds: CSR is chosen because a graph of edges fits in 0.4 GB instead of several.
Breadth-first traversal: BFS in linear time
Breadth-first search (BFS) visits vertices in increasing distance layers from source using a queue: remove a vertex, inspect each neighbor, and label previously unlabeled ones with the vertex’s label plus one and enqueue them.
Proof
Induct on that vertices at distance receive label and enter the queue after all at distance and before any at distance . For there is only . Assume true through . A vertex at distance has a predecessor at distance and none at a shorter distance (otherwise its own distance would be shorter). Since those at distance leave the queue before those at , no vertex farther than can yet be discovered, because its predecessors are at distance at least ; when the first predecessor of leaves the queue, receives label if not already labeled (and could not have a smaller label by induction). Thus ‘s label is and it enters after all vertices at distance . Each vertex enters at most once and its list is examined once: , including label initialization. With a matrix, one row of cells is scanned per dequeued vertex.
∎BFS also returns a shortest-path tree in edges (parent of is its discoverer). The queue needs popleft in : with a Python list, cola.pop(0) shifts every element and makes traversal quadratic, a classic error measured in the lab. Search in implicit state spaces, where the graph is generated instead of stored, is covered in the search lesson; here graphs are in memory. BFS does not handle weighted shortest paths: use Dijkstra, replacing the queue with a priority queue.
Depth-first search: times, parentheses and edges
Depth-first search (DFS) replaces the queue with the recursion stack: follow an edge as far as possible, backtracking only when a vertex is exhausted. What matters is not visit order but two numbers recorded per vertex, with a clock ticking once per event.
DFS(G): VISITAR(u):
para cada vértice u: color[u] = blanco reloj += 1; d[u] = reloj; color[u] = gris
reloj = 0 para cada v en Adj[u]:
para cada vértice u: si color[v] == blanco: padre[v] = u; VISITAR(v)
si color[u] == blanco: VISITAR(u) color[u] = negro; reloj += 1; f[u] = reloj
A vertex is white until discovered, gray while its call is open (discovered but not finished examining neighbors), and black when finished. Numbers (discovery) and (finish) are all distinct and range from to . Calls started by the main loop are roots of a search forest, and padre gives its tree edges. Each vertex is visited once and each adjacency list traversed once, costing with lists or CSR.
What the figure shows is a theorem.
Proof
Without loss of generality let . There are two cases because all times differ.
If , then is discovered while is gray, inside ‘s open call. Everything discovered while a call is open hangs below it in the forest, so is a descendant of . Moreover ‘s call finishes before ‘s (calls nest like a stack), so and ‘s interval is contained in ‘s.
If , intervals are disjoint. Neither is the other’s descendant: a descendant is discovered while its ancestor is gray, and here is discovered after finishes. The three cases are mutually exclusive because their time conditions are.
∎The theorem describes times, but not when a vertex becomes another’s descendant. The second result answers that, relating graph structure to forest structure.
Proof
() If is a descendant of , tree path has every with as a descendant of , so they are discovered after : at they are white.
() Let be a white path at time , and suppose some is not a descendant of . Take the first, , with . Then is a descendant of (or is ), hence . When edge is examined, is either white (then becomes a child of , contradicting the assumption) or already discovered; either way it is discovered before finishes. Since it was white at , , and by the parenthesis theorem is a descendant of . Contradiction.
∎Edge classification
Each edge is examined exactly once, when reaches it in its list, and ‘s color then classifies it:
| Color of when examining | Type | Intervals | What is to |
|---|---|---|---|
| white | tree | nested in | child |
| gray | back | nested in (or ) | ancestor |
| black, with | forward | nested in | non-child descendant |
| black, with | cross | disjoint, | neither |
The table follows from the parenthesis theorem. If is gray, its call remains open and contains ‘s: is an ancestor of (or itself for a loop). If is black and discovered after , its interval lies inside ‘s. If black and discovered earlier, it cannot contain (because already finished and remains open), so the intervals are disjoint and . Classification depends on the search (vertex and neighbor order), not just the graph; what does not depend on it is what we prove using it.
Proof
Let be an edge and the endpoint from which it is first examined. If were black then, would have finished and examined all its edges, including : the edge would already have been examined, contradicting the assumption. Thus is white (tree) or gray (back).
∎This absence of cross edges makes the structure of undirected graphs so clean in the final sections: everything that is not a tree edge connects a vertex to an ancestor.
Topological order
Proof
If there is a cycle , a topological order gives positions with , absurd. Conversely, a DAG with vertices has one without incoming edges: if every vertex had a predecessor, walking backward from any vertex would chain vertices and, by the pigeonhole principle, one repeats, closing a cycle. Place that vertex first, remove it, and induct on the remaining graph, still acyclic.
∎The proof is already an algorithm, the first of two.
Kahn: remove sources
Kahn’s algorithm stores each vertex’s in-degree, maintains a queue of those with degree and repeats: remove one, append it to the order and decrement its successors’ degrees; those reaching enter the queue. Cost with lists or CSR.
Proof
A vertex enters the order when all its predecessors already have, so edges always point forward. If the algorithm stops with , no vertex of has remaining degree , and ‘s remaining degree counts predecessors of still unplaced, namely those in . Each vertex of therefore has at least one predecessor in , and the preceding pigeonhole argument yields a cycle within . If the graph is acyclic, cannot happen.
∎This gives a certificate: the algorithm does not merely say “yes” or “no” but returns something independently checkable with less work than the original computation. Verify an order in by checking every edge points forward, and a cycle in by checking every step is an edge. This is the difference between “this cannot be ordered” and “this cannot be ordered, and here is the proof”.
DFS: order by finish time
The second algorithm follows from the parenthesis theorem. The idea: if edge exists, vertex must finish before , because cannot close while remains pending.
Proof
For a tree or forward edge, descends from and its interval lies inside ‘s, hence . For a cross edge, intervals are disjoint and .
∎Proof
Without back edges, the lemma says every edge satisfies , so precedes in decreasing order. With back edge , is gray, hence an ancestor of (or ): the tree path from to and edge form a cycle.
∎Together these theorems also show that a directed graph is acyclic if and only if its DFS has no back edges; “cycle implies back edge” has a more direct proof using the white-path theorem, requested in the first exercise. Decreasing order needs no sorting: append each vertex to a list when it finishes and read it backward. The stated cycle comes from following padre from to .
Both algorithms are linear and yield similar results, but differ in character. Kahn works in waves (vertices freed simultaneously form a wave and can run in parallel, so the wave count is longest-path length plus one, the critical path); it underlies schedulers and can use a priority queue for, say, the lexicographically smallest order. DFS needs neither in-degrees nor the transpose and leads into components and bridges. Topological order is unique if and only if Kahn never has two vertices in its queue simultaneously, that is, if the graph has a path visiting every vertex.
A network’s backward pass as an example
An expression such as defines a graph: each operation is a node with edges to operands. To propagate gradients, visit each node after all consumers; a DFS postorder starting at and descending to operands puts operands before consumers, so reversing it is valid. The lab builds minimal autograd exactly this way and shows what happens using preorder (discovery order) instead of reverse postorder: the gradient is wrong because a node with two consumers propagates its gradient before receiving all of the second’s contribution. Karpathy’s micrograd implementation constructs the order with DFS; PyTorch autograd keeps a pending-dependency count per node and executes it at zero, which is Kahn.
Strongly connected components
In an undirected graph, “reachable from” is symmetric and connected components are its equivalence classes. In a directed graph we require both directions.
Proof
A cycle with distinct components would give paths both ways between all vertices of all (within each component by definition and between them via edges), so they would be one component.
∎Do not confuse strongly connected components with connected components of the underlying undirected graph (ignoring direction): graph is connected and has three strongly connected components. Condensation solves the opening problem generally: even with cycles, compile modules in mutually dependent groups, topologically ordered.
Kosaraju: two searches and the transpose graph
For a component , let and .
Proof
First case, . Let be the first discovered vertex of . At time all vertices of and are white, with a white path from to each: within by strong connectivity, and to across edge and within . By the white-path theorem, all descend from , so for every , in particular .
Second case, . Let be the first discovered vertex of . At , every is white and becomes a descendant of . From no vertex of is reachable: otherwise, since reaches , they would be the same component. Thus all vertices of are white at and not descendants of , so they are discovered after finishes. Thus .
∎The lemma says ordering components by decreasing gives a topological order of the condensation: if an edge goes from to , the greater is . (Vertices ordered by decreasing are not grouped by component, but the first vertex of each marks .) Kosaraju’s algorithm (also published independently by Sharir) exploits this:
- DFS on to obtain finish times.
- Build the transpose graph (same edges reversed). It has the same strongly connected components as .
- DFS on , choosing roots by decreasing (those of ). Each resulting forest tree is one component.
Proof
Induct on trees, assuming each earlier tree was a complete component, so components are entirely visited or entirely unvisited. Let be the unvisited vertex with greatest and its component: because is entirely unvisited and has greatest among unvisited vertices, . Inside everything is reachable from in , so the tree contains . It remains to show it cannot leave. An edge of from a vertex of to one in component is an edge of from to , and the lemma gives ; but contains the unvisited vertex of greatest , so must already be visited, and search does not enter visited vertices. Cost is two DFS traversals plus transpose construction (counting sort).
∎An immediate consequence of the lemma, to prove in an exercise, is that the vertex of greatest belongs to a source component of the condensation (no incoming edge from another component). Kosaraju is easy to remember and prove. Its cost is the transpose and a second pass; Tarjan solves it in one.
Tarjan: one pass with a stack
Tarjan (1972) computes components in one DFS without a transpose, using two numbers per vertex and an explicit stack of discovered vertices not yet assigned to a component.
- : discovery order ().
- : the smallest index reachable from ‘s subtree following tree edges and at most one edge to a vertex still on the stack.
When examining edge : if is new, descend and on return ; if is still on the stack, ; if has left the stack, ignore it. When exhausts its edges and , is a component root: pop through inclusive; the popped vertices are the component.
Proof
Let be the first discovered vertex of ‘s component. By the white-path theorem all vertices of ‘s component descend from it (at its discovery they are white and connected to by paths within the component). Induct over successive finish events, assuming all earlier pops were complete components. This implies invariant (I): a discovered vertex is on the stack if and only if has not yet finished.
() Show implies . If , there would be an edge with in ‘s subtree, on the stack then, and . By (I), was open, hence gray, an ancestor of ; since it is a proper ancestor of . Then reaches by the tree, reaches by the tree, , and reaches within its component: belongs to ‘s component and was discovered before , contradicting .
() Show implies . If , is an ancestor of and remains open. Let be the first edge on a path from to within the component that leaves ‘s subtree (it exists because is outside it). When examined, had already been discovered (if white, it would have become a descendant of , hence of ), and since it is not a descendant of and was discovered before finished, . Also belongs to ‘s still-open component, so by (I) it was on the stack. Examining gives , and that value propagates up the tree to : .
It remains to see what is popped when root finishes. All of ‘s component is on the stack above (descendants discovered later, and not yet popped by (I)). A vertex above on the stack descends from and its remains open: it is or a proper ancestor of ; in the latter case reaches by the tree, reaches , and reaches , so would belong to ‘s component with , a contradiction. Thus exactly ‘s component is popped.
Components emerge in reverse topological order: if an edge goes from to , Kosaraju’s lemma gives , so ‘s root finishes and is popped before ‘s. Each vertex is pushed and popped once and each edge examined once: .
∎Two observations. First, what closes a component is not the value of an arbitrary vertex but its root: other component vertices have , as shown for and . Second, output numbering already gives a topological order of the condensation (read backward), for free: 2-SAT below uses this, avoiding construction and sorting of the condensation.
Recursion: why iteration is needed
Recursive DFS uses one call per vertex of the active path. On a path of one hundred thousand vertices, the search descends one hundred thousand levels; recursion that deep exceeds Python’s limit (1000 calls by default, and raising it with sys.setrecursionlimit can crash the interpreter by overflowing the C stack). The solution already seen above is an explicit stack with, for every open vertex, a pointer to the next edge to inspect. With CSR the pointer is an integer traversing indices[indptr[u]:indptr[u+1]]. The iterative version performs exactly the same operations and is implemented in the lab.
2-SAT with strongly connected components
A 2-SAT formula is a conjunction of two-literal clauses (2-SAT). Each clause is equivalent to two implications, and . The implication graph has one vertex per literal (thus vertices for variables) and one edge per implication. It is skew-symmetric under negation (not to be confused with an antisymmetric relation): there is an edge if and only if there is .
Proof
If and share a component, implication paths and exist, and no value of satisfies them all. Conversely, assume no variable shares a component with its negation and let be the position of ‘s component in a condensation topological order. Since , the rule “ is true iff ” consistently assigns each variable. Suppose it violates a clause, meaning an implication has true and false. Then and . Since is an edge, , and by symmetry gives . Chaining them gives , absurd.
∎With Tarjan numbering, already reverse topological order, the rule needs no extra computation: the variable is true if its literal’s component number is smaller than its negation’s.
Module dependencies
Everything comes together in the opening problem. The figure uses eleven modules of a fictional project: edge means “ must be ready before ”, i.e. depends on .
The shortest cycle is shown to the developer. It has the fewest edges among cycles passing through a component vertex: find it with BFS from each component vertex (distance back to the source), costing for a component with vertices and internal edges. Finding the smallest set of edges whose removal breaks all cycles (a feedback arc set) is NP-hard in general; the figure’s check that one edge suffices is polynomial, testing each edge with an acyclicity test.
Bridges, articulation points and biconnected components
For undirected graphs, a robustness question is which elements disconnect the graph when removed.
Testing each element separately (remove it and count components) would cost . DFS solves it in one pass because, in an undirected graph, everything that is not a tree edge is a back edge to an ancestor. Let be the smallest reachable from ‘s subtree with one back edge:
Compute it as each vertex finishes, as in Tarjan, as the minimum of three things: its own , the values of back edges leaving , and the values of its tree children . One detail is essential: the tree edge used to reach does not count as a back edge to its parent (otherwise no edge would be a bridge). Identify it by edge ID, not endpoint, which also handles parallel edges correctly.
Proof
Everything leaving ‘s subtree is tree edge or a back edge to an ancestor of (there are no cross edges: an edge between ‘s subtree and an outside vertex connects ancestor to descendant).
(1) A back edge closes a cycle with the tree path, so removing it disconnects nothing. For : the only vertices with on ‘s ancestor path are and those above it, with . If there is a back edge from ‘s subtree to or above, and the subtree remains connected to the rest without edge . If , no such back edge exists and is the only edge between ‘s subtree and the rest: removing it disconnects it.
(2) If a child satisfies , ‘s subtree connects outside only through (its back edges reach at most ), and removing isolates it from , which exists because is not the root. If all children satisfy , each child subtree has a back edge to a proper ancestor of ; the tree without ‘s subtree remains connected (it contains the root), and every child subtree joins it, so is connected.
(3) Without the root, its children’s subtrees have no edges between them (they would be cross edges), so at least two remain separate; one forms a single connected block.
∎Biconnected components emerge from the same traversal with an edge stack: when child of finishes with , pop edges through and those form a block. Articulation points are vertices belonging to multiple blocks. Removing all bridges leaves 2-edge-connected components, which, contracted to one vertex each, form a tree if the graph is connected (the bridge tree).
Implementation from scratch
Five cells build a small CSR-based library, all iterative, each part checked against networkx on random graphs. They share a session: later cells use earlier definitions.
First cell: CSR using counting sort, BFS with deque, and iterative DFS with a pointer per vertex, computing , , parent, finish order and edge classification. The parenthesis theorem is checked on each result and the list.pop(0) queue error measured.
import random
import time
from collections import deque
import networkx as nx
import numpy as np
class CSR:
"""Grafo dirigido en formato CSR: indptr (n + 1 posiciones) e indices (m posiciones)."""
def __init__(self, n, aristas):
indptr = [0] * (n + 1)
for u, _ in aristas: # 1) grados de salida, desplazados una posición
indptr[u + 1] += 1
for i in range(n): # 2) suma de prefijos: indptr[u] es dónde empieza la fila u
indptr[i + 1] += indptr[i]
siguiente = indptr[:-1] # una copia: la próxima posición libre de cada fila
indices = [0] * len(aristas)
for u, v in aristas: # 3) colocación: cada arista va a su hueco
indices[siguiente[u]] = v
siguiente[u] += 1
self.n, self.m = n, len(aristas)
self.indptr, self.indices = indptr, indices
def vecinos(self, u):
return self.indices[self.indptr[u]:self.indptr[u + 1]]
def traspuesto(self):
return CSR(self.n, [(v, u) for u in range(self.n) for v in self.vecinos(u)])
def bytes_numpy(self):
"""Lo que ocuparía con índices de 32 bits en arrays de NumPy."""
return np.array(self.indptr, dtype=np.int32).nbytes + np.array(self.indices, dtype=np.int32).nbytes
def bfs(g, origen):
"""Distancias (en aristas) desde el origen; -1 si no es alcanzable. O(n + m)."""
ip, ix = g.indptr, g.indices
dist = [-1] * g.n
dist[origen] = 0
cola = deque([origen]) # deque: popleft en O(1); list.pop(0) sería O(n)
while cola:
u = cola.popleft()
for k in range(ip[u], ip[u + 1]):
v = ix[k]
if dist[v] < 0:
dist[v] = dist[u] + 1
cola.append(v)
return dist
def dfs(g):
"""DFS iterativa con tiempos d y f, padres, orden de finalización y clasificación de aristas."""
n, ip, ix = g.n, g.indptr, g.indices
d, f, padre = [0] * n, [0] * n, [-1] * n
siguiente = ip[:-1] # puntero a la próxima arista de cada vértice
tipos = {"arbol": 0, "retroceso": 0, "avance": 0, "cruzada": 0}
fin, reloj = [], 0
for s in range(n):
if d[s]:
continue
reloj += 1
d[s] = reloj
pila = [s]
while pila:
u = pila[-1]
if siguiente[u] < ip[u + 1]:
v = ix[siguiente[u]]
siguiente[u] += 1
if not d[v]: # blanco
tipos["arbol"] += 1
padre[v] = u
reloj += 1
d[v] = reloj
pila.append(v)
elif not f[v]: # gris: sigue abierto
tipos["retroceso"] += 1
elif d[u] < d[v]: # negro y descubierto después
tipos["avance"] += 1
else: # negro y descubierto antes
tipos["cruzada"] += 1
else:
reloj += 1
f[u] = reloj
fin.append(u)
pila.pop()
return d, f, padre, fin, tipos
def aleatorio(n, m, semilla):
r = random.Random(semilla)
return [(r.randrange(n), r.randrange(n)) for _ in range(m)]
# el ejemplo de la figura: u v w x y z = 0..5
ej = CSR(6, [(0, 1), (0, 3), (1, 4), (2, 4), (2, 5), (3, 1), (4, 3), (5, 5)])
d, f, padre, fin, tipos = dfs(ej)
print("intervalos [d, f]:", {"uvwxyz"[v]: (d[v], f[v]) for v in range(6)})
print("aristas por tipo:", tipos)
def parentesis_ok(d, f):
"""Teorema del paréntesis: dos intervalos son disjuntos o uno contiene al otro, nunca se cruzan."""
n = len(d)
for u in range(n):
for v in range(u + 1, n):
disjuntos = f[u] < d[v] or f[v] < d[u]
anidados = (d[u] < d[v] < f[v] < f[u]) or (d[v] < d[u] < f[u] < f[v])
if not (disjuntos or anidados):
return False
return True
# contraste con networkx: orden de descubrimiento, orden de finalización y distancias de BFS
desacuerdos = 0
for semilla in range(60):
n = random.Random(semilla).randint(2, 40)
aristas = list(dict.fromkeys(aleatorio(n, random.Random(semilla + 1000).randint(0, 3 * n), semilla)))
g = CSR(n, aristas)
d, f, padre, fin, tipos = dfs(g)
G = nx.DiGraph()
G.add_nodes_from(range(n))
G.add_edges_from(aristas)
ok = sorted(range(n), key=lambda v: d[v]) == list(nx.dfs_preorder_nodes(G))
ok = ok and fin == list(nx.dfs_postorder_nodes(G)) and parentesis_ok(d, f)
dist, ref = bfs(g, 0), nx.single_source_shortest_path_length(G, 0)
ok = ok and all(dist[v] == ref.get(v, -1) for v in range(n))
desacuerdos += not ok
print("grafos aleatorios con algún desacuerdo frente a networkx:", desacuerdos, "de 60")
def bfs_lista(g, origen):
"""BFS con list.pop(0): el error típico."""
ip, ix = g.indptr, g.indices
dist = [-1] * g.n
dist[origen] = 0
cola = [origen]
while cola:
u = cola.pop(0) # O(longitud de la cola)
for k in range(ip[u], ip[u + 1]):
v = ix[k]
if dist[v] < 0:
dist[v] = dist[u] + 1
cola.append(v)
return dist
for n in (10000, 20000, 40000):
estrella = CSR(n, [(0, v) for v in range(1, n)]) # el origen tiene n - 1 vecinos: la cola llega a medir n - 1
t0 = time.perf_counter(); bfs(estrella, 0); t1 = time.perf_counter(); bfs_lista(estrella, 0); t2 = time.perf_counter()
print(f"n = {n:6d}: deque {1000 * (t1 - t0):7.1f} ms list.pop(0) {1000 * (t2 - t1):8.1f} ms")The figure example yields the intervals and classifications seen above (4 tree, 2 back, 1 forward and 1 cross edge). Discovery and finish orders match networkx across random graphs, the parenthesis theorem holds throughout, and BFS distances match too. The final test quantifies the queue error: in a star the queue reaches elements and each pop(0) shifts all of them.
Second cell: both topological sorting algorithms, their certificates and verifiers, on random graphs with and without cycles.
def kahn(g):
"""Orden topológico por grados de entrada. Devuelve (orden, grado_restante): hay ciclo si len(orden) < n."""
n, ip, ix = g.n, g.indptr, g.indices
grado = [0] * n
for v in ix:
grado[v] += 1
cola = deque(v for v in range(n) if grado[v] == 0)
orden = []
while cola:
u = cola.popleft()
orden.append(u)
for k in range(ip[u], ip[u + 1]):
v = ix[k]
grado[v] -= 1
if grado[v] == 0:
cola.append(v)
return orden, grado
def ciclo_de_los_restantes(g, orden):
"""Certificado de ciclo a partir de lo que Kahn no pudo colocar: todo vértice restante tiene un predecesor restante."""
resto = set(range(g.n)) - set(orden)
gt = g.traspuesto()
v = next(iter(resto))
visto, camino = {}, []
while v not in visto: # caminar hacia atrás: tarde o temprano se repite un vértice
visto[v] = len(camino)
camino.append(v)
v = next(w for w in gt.vecinos(v) if w in resto)
return camino[visto[v]:][::-1] # el ciclo, ya en el sentido de las aristas
def topologico_dfs(g):
"""Orden por tiempo de finalización decreciente; si la DFS ve una arista de retroceso devuelve su ciclo."""
n, ip, ix = g.n, g.indptr, g.indices
color, padre, siguiente, fin = [0] * n, [-1] * n, ip[:-1], []
for s in range(n):
if color[s]:
continue
color[s] = 1
pila = [s]
while pila:
u = pila[-1]
if siguiente[u] < ip[u + 1]:
v = ix[siguiente[u]]
siguiente[u] += 1
if color[v] == 0:
color[v], padre[v] = 1, u
pila.append(v)
elif color[v] == 1: # arista de retroceso u -> v: el camino de árbol v ... u la cierra
ciclo, x = [u], u
while x != v:
x = padre[x]
ciclo.append(x)
return "ciclo", ciclo[::-1]
else:
color[u] = 2
fin.append(u)
pila.pop()
return "orden", fin[::-1]
def verificar_orden(g, orden):
"""Un certificado de orden se comprueba en O(n + m): cada arista debe ir hacia delante."""
pos = {v: i for i, v in enumerate(orden)}
return len(pos) == g.n and all(pos[u] < pos[v] for u in range(g.n) for v in g.vecinos(u))
def verificar_ciclo(g, ciclo):
"""Un certificado de ciclo se comprueba en O(longitud): cada paso debe ser una arista."""
return len(ciclo) >= 1 and all(ciclo[(i + 1) % len(ciclo)] in g.vecinos(c) for i, c in enumerate(ciclo))
rnd = random.Random(7)
resumen = {"acíclicos": 0, "cíclicos": 0}
for _ in range(200):
n = rnd.randint(2, 30)
perm = list(range(n))
rnd.shuffle(perm)
aristas = [tuple(sorted((rnd.randrange(n), rnd.randrange(n)))) for _ in range(rnd.randint(0, 2 * n))]
aristas = [(perm[a], perm[b]) for a, b in aristas if a != b] # un DAG con los vértices barajados
if rnd.random() < 0.5 and aristas:
aristas.append((rnd.randrange(n), rnd.randrange(n))) # con probabilidad 1/2, una arista que puede cerrar un ciclo
g = CSR(n, aristas)
G = nx.DiGraph(aristas)
G.add_nodes_from(range(n))
orden, _ = kahn(g)
tipo, cert = topologico_dfs(g)
if nx.is_directed_acyclic_graph(G):
resumen["acíclicos"] += 1
assert len(orden) == n and verificar_orden(g, orden)
assert tipo == "orden" and verificar_orden(g, cert)
else:
resumen["cíclicos"] += 1
assert len(orden) < n and verificar_ciclo(g, ciclo_de_los_restantes(g, orden))
assert tipo == "ciclo" and verificar_ciclo(g, cert)
print("200 grafos aleatorios:", resumen, "- todos los certificados verifican")
# el proyecto de la figura, con y sin el import circular models <- api
modulos = ["config", "logging", "utils", "db", "cache", "models", "schemas", "auth", "api", "cli", "app"]
nombres = {m: i for i, m in enumerate(modulos)}
dep = [("config", "logging"), ("config", "db"), ("config", "cache"), ("logging", "db"), ("utils", "db"), ("utils", "cache"),
("utils", "schemas"), ("db", "models"), ("models", "schemas"), ("models", "auth"), ("cache", "auth"), ("schemas", "api"),
("auth", "api"), ("api", "cli"), ("api", "app"), ("cli", "app")]
aristas = [(nombres[a], nombres[b]) for a, b in dep]
orden, _ = kahn(CSR(len(modulos), aristas))
print("orden de compilación:", " -> ".join(modulos[v] for v in orden))
g2 = CSR(len(modulos), aristas + [(nombres["api"], nombres["models"])])
orden2, _ = kahn(g2)
ciclo = ciclo_de_los_restantes(g2, orden2)
print("con el import circular, Kahn coloca", len(orden2), "de", len(modulos), "y el certificado es:", " -> ".join(modulos[v] for v in ciclo + ciclo[:1]))
tipo, cert = topologico_dfs(g2)
print("la DFS encuentra otro ciclo:", " -> ".join(modulos[v] for v in cert + cert[:1]))Both algorithms agree with networkx about cycle existence, and both certificates pass verification. In the project figure Kahn places 5 of 11 modules and stalls, and both methods return the same three-module cycle (from a different starting point). But it is not the only one: the component also contains the cycle models, auth, api. Certificates are not unique; each algorithm gives the first it finds.
Third cell: minimal autograd with topological order in action. The gradient uses DFS reverse postorder and is compared with finite differences and preorder, which is not topological.
import math
class Valor:
"""Un escalar con historia: sabe de qué operandos viene y cómo reparte el gradiente entre ellos."""
def __init__(self, dato, operandos=()):
self.dato, self.grad, self.operandos = dato, 0.0, operandos
self.repartir = lambda: None
def __add__(self, o):
r = Valor(self.dato + o.dato, (self, o))
def repartir():
self.grad += r.grad
o.grad += r.grad
r.repartir = repartir
return r
def __mul__(self, o):
r = Valor(self.dato * o.dato, (self, o))
def repartir():
self.grad += o.dato * r.grad
o.grad += self.dato * r.grad
r.repartir = repartir
return r
def tanh(self):
t = math.tanh(self.dato)
r = Valor(t, (self,))
def repartir():
self.grad += (1 - t * t) * r.grad
r.repartir = repartir
return r
def recorrido(self):
"""DFS iterativa desde este nodo hacia sus operandos. Devuelve (preorden, postorden)."""
visto, pre, post, pila = {id(self)}, [self], [], [(self, 0)]
while pila:
nodo, i = pila.pop()
if i < len(nodo.operandos):
pila.append((nodo, i + 1))
h = nodo.operandos[i]
if id(h) not in visto:
visto.add(id(h))
pre.append(h)
pila.append((h, 0))
else:
post.append(nodo) # todos sus operandos ya han terminado: van antes en el postorden
return pre, post
def backward(self, orden="topologico"):
pre, post = self.recorrido()
secuencia = post[::-1] if orden == "topologico" else pre # reverso del postorden, o el preorden (incorrecto)
self.grad = 1.0
for nodo in secuencia:
nodo.repartir()
def funcion(a, b, c):
s = a * b # s lo usan dos nodos distintos: un rombo en el grafo
u = s + c
w = s * c
return (u * w).tanh()
x0 = (0.7, -1.3, 0.4)
def gradientes(orden):
a, b, c = (Valor(t) for t in x0)
funcion(a, b, c).backward(orden)
return [a.grad, b.grad, c.grad]
h = 1e-6
numerico = []
for i in range(3):
mas, menos = list(x0), list(x0)
mas[i] += h
menos[i] -= h
numerico.append((funcion(*[Valor(t) for t in mas]).dato - funcion(*[Valor(t) for t in menos]).dato) / (2 * h))
print("diferencias finitas :", np.round(numerico, 6))
print("orden topológico (f) :", np.round(gradientes("topologico"), 6))
print("preorden (d) :", np.round(gradientes("preorden"), 6))With reverse postorder all three gradients match finite differences. With preorder (here , , , , , , , ), gradients of and are wrong: node is used by and , and preorder visits immediately after , before has sent its contribution. ’s gradient is correct, but not because the order is valid: is a leaf propagating nothing, and the two nodes sending it gradients, and , each have one consumer, so already have their full gradients when propagating.
Fourth cell: iterative Tarjan, Kosaraju and 2-SAT, checked against networkx and scipy, and failure of the recursive version.
import sys
from itertools import product
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
def tarjan(g):
"""Componentes fuertemente conexas, iterativo. comp[v] numera las componentes en el orden en que se cierran:
toda arista u -> v cumple comp[u] >= comp[v] (la primera componente es un sumidero)."""
n, ip, ix = g.n, g.indptr, g.indices
idx, low, comp = [-1] * n, [0] * n, [-1] * n
siguiente, pila, llamadas = ip[:-1], [], []
contador = nc = 0
for s in range(n):
if idx[s] >= 0:
continue
idx[s] = low[s] = contador
contador += 1
pila.append(s)
llamadas.append(s)
while llamadas:
u = llamadas[-1]
if siguiente[u] < ip[u + 1]:
v = ix[siguiente[u]]
siguiente[u] += 1
if idx[v] < 0: # vértice nuevo: arista de árbol
idx[v] = low[v] = contador
contador += 1
pila.append(v)
llamadas.append(v)
elif comp[v] < 0 and idx[v] < low[u]: # sigue en la pila: puede volver a él
low[u] = idx[v]
else:
llamadas.pop()
if low[u] == idx[u]: # u es la raíz de una componente: se desapila hasta u
while True:
w = pila.pop()
comp[w] = nc
if w == u:
break
nc += 1
if llamadas and low[u] < low[llamadas[-1]]:
low[llamadas[-1]] = low[u]
return comp, nc
def tarjan_recursivo(g):
"""La versión de manual, recursiva. Solo para ver cómo falla."""
n, ip, ix = g.n, g.indptr, g.indices
idx, low, comp, pila = [-1] * n, [0] * n, [-1] * n, []
estado = {"c": 0, "nc": 0}
def visitar(u):
idx[u] = low[u] = estado["c"]
estado["c"] += 1
pila.append(u)
for k in range(ip[u], ip[u + 1]):
v = ix[k]
if idx[v] < 0:
visitar(v)
low[u] = min(low[u], low[v])
elif comp[v] < 0:
low[u] = min(low[u], idx[v])
if low[u] == idx[u]:
while True:
w = pila.pop()
comp[w] = estado["nc"]
if w == u:
break
estado["nc"] += 1
for s in range(n):
if idx[s] < 0:
visitar(s)
return comp, estado["nc"]
def kosaraju(g):
"""Dos DFS: una sobre G para el orden de finalización y otra sobre el traspuesto, en orden de f decreciente."""
_, _, _, fin, _ = dfs(g)
gt = g.traspuesto()
comp, nc = [-1] * g.n, 0
for s in reversed(fin):
if comp[s] >= 0:
continue
comp[s] = nc
pila = [s]
while pila:
u = pila.pop()
for v in gt.vecinos(u):
if comp[v] < 0:
comp[v] = nc
pila.append(v)
nc += 1
return comp, nc
def particion(comp):
grupos = {}
for v, c in enumerate(comp):
grupos.setdefault(c, set()).add(v)
return {frozenset(s) for s in grupos.values()}
# el ejemplo de la figura: a..h
g = CSR(8, [(0, 1), (1, 2), (1, 4), (1, 5), (2, 3), (2, 6), (3, 2), (3, 7), (4, 0), (4, 5), (5, 6), (6, 5), (6, 7), (7, 7)])
comp, nc = tarjan(g)
print("componentes de Tarjan, en orden de cierre:", [["abcdefgh"[v] for v in range(8) if comp[v] == c] for c in range(nc)])
# contraste con networkx, scipy y Kosaraju
rnd = random.Random(3)
desacuerdos = 0
for _ in range(300):
n = rnd.randint(1, 40)
aristas = [(rnd.randrange(n), rnd.randrange(n)) for _ in range(rnd.randint(0, 2 * n))]
g = CSR(n, aristas)
G = nx.DiGraph(aristas)
G.add_nodes_from(range(n))
ref = {frozenset(c) for c in nx.strongly_connected_components(G)}
comp_t, _ = tarjan(g)
comp_k, _ = kosaraju(g)
M = csr_matrix((np.ones(len(aristas)), ([a for a, _ in aristas], [b for _, b in aristas])), shape=(n, n))
_, lab_s = connected_components(M, directed=True, connection="strong")
ok = particion(comp_t) == ref and particion(comp_k) == ref and particion(list(lab_s)) == ref
ok = ok and all(comp_t[u] >= comp_t[v] for u, v in aristas) # Tarjan: orden topológico inverso
ok = ok and all(comp_k[u] <= comp_k[v] for u, v in aristas) # Kosaraju: orden topológico directo
desacuerdos += not ok
print("desacuerdos entre Tarjan, Kosaraju, networkx y scipy en 300 grafos:", desacuerdos)
# recursión frente a iteración: un camino de miles de vértices
n = 20000
camino = CSR(n, [(i, i + 1) for i in range(n - 1)])
print("límite de recursión de este intérprete:", sys.getrecursionlimit())
try:
tarjan_recursivo(camino)
print("la versión recursiva terminó")
except RecursionError:
print(f"versión recursiva con n = {n}: RecursionError")
print(f"versión iterativa con n = {n}: {tarjan(camino)[1]} componentes (cada vértice, la suya)")
anillo = CSR(n, [(i, (i + 1) % n) for i in range(n)])
print("anillo del mismo tamaño:", tarjan(anillo)[1], "componente")
def dos_sat(nvars, clausulas):
"""Cláusulas (a o b) con literales +i / -i (variables 1..nvars). Devuelve una asignación o None."""
lit = lambda x: 2 * (abs(x) - 1) + (x < 0) # 2i = x_i verdadera, 2i + 1 = x_i falsa
neg = lambda l: l ^ 1
aristas = []
for a, b in clausulas:
aristas += [(neg(lit(a)), lit(b)), (neg(lit(b)), lit(a))] # la cláusula (a o b): no a implica b, y no b implica a
comp, _ = tarjan(CSR(2 * nvars, aristas))
if any(comp[2 * i] == comp[2 * i + 1] for i in range(nvars)):
return None
return [comp[2 * i] < comp[2 * i + 1] for i in range(nvars)] # verdadera si su componente se cierra antes (va después en topológico)
def satisface(asig, clausulas):
val = lambda x: asig[abs(x) - 1] == (x > 0)
return all(val(a) or val(b) for a, b in clausulas)
rnd = random.Random(5)
resultados = {"sat": 0, "unsat": 0}
for _ in range(400):
nv = rnd.randint(2, 7)
cl = [(rnd.choice([-1, 1]) * rnd.randint(1, nv), rnd.choice([-1, 1]) * rnd.randint(1, nv)) for _ in range(rnd.randint(1, 3 * nv))]
fuerza_bruta = any(satisface(a, cl) for a in product([False, True], repeat=nv))
sol = dos_sat(nv, cl)
assert (sol is not None) == fuerza_bruta
if sol is not None:
assert satisface(sol, cl)
resultados["sat" if fuerza_bruta else "unsat"] += 1
print("2-SAT frente a fuerza bruta en 400 fórmulas:", resultados)The four components emerge in the figure’s order. Tarjan, Kosaraju, networkx and scipy give the same partition on every random graph; Tarjan numbers components in reverse topological order and Kosaraju forward, as theory predicts. The recursive version fails on a twenty-thousand-vertex path, the iterative one does not, and component-based 2-SAT agrees with brute force on four hundred formulas using the proof’s assignment.
Fifth cell: bridges and articulation points in iterative DFS, with edge IDs, checked against networkx.
def puentes_y_articulaciones(n, aristas):
"""Puentes (como índices de arista) y puntos de articulación de un grafo no dirigido, en una DFS iterativa.
Las aristas llevan identificador para tratar bien las paralelas: solo se salta la arista por la que se llegó."""
inc = [[] for _ in range(n)]
for i, (u, v) in enumerate(aristas):
inc[u].append((v, i))
inc[v].append((u, i))
d, low, padre_arista = [0] * n, [0] * n, [-1] * n
siguiente = [0] * n
puentes, articulacion, reloj = [], [False] * n, 0
for s in range(n):
if d[s]:
continue
reloj += 1
d[s] = low[s] = reloj
pila, hijos_raiz = [s], 0
while pila:
u = pila[-1]
if siguiente[u] < len(inc[u]):
v, i = inc[u][siguiente[u]]
siguiente[u] += 1
if i == padre_arista[u]:
continue # la arista por la que llegamos a u no cuenta como retroceso
if not d[v]: # arista de árbol
reloj += 1
d[v] = low[v] = reloj
padre_arista[v] = i
pila.append(v)
if u == s:
hijos_raiz += 1
else: # arista de retroceso (o su copia vista desde el ascendiente)
low[u] = min(low[u], d[v])
else:
pila.pop()
if pila:
p = pila[-1]
low[p] = min(low[p], low[u])
if low[u] > d[p]:
puentes.append(padre_arista[u])
if p != s and low[u] >= d[p]:
articulacion[p] = True
if hijos_raiz >= 2:
articulacion[s] = True
return puentes, [v for v in range(n) if articulacion[v]]
# el grafo de la figura: a..i
aristas = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 5), (5, 6), (6, 3), (6, 7), (7, 8)]
pu, ar = puentes_y_articulaciones(9, aristas)
print("puentes:", [("abcdefghi"[aristas[i][0]] + "-" + "abcdefghi"[aristas[i][1]]) for i in sorted(pu)],
" articulaciones:", ["abcdefghi"[v] for v in ar])
# contraste con networkx, con aristas paralelas incluidas
rnd = random.Random(2)
desacuerdos = 0
for _ in range(400):
n = rnd.randint(2, 30)
aristas = []
for _ in range(rnd.randint(0, int(1.4 * n))):
a, b = rnd.randrange(n), rnd.randrange(n)
if a != b:
aristas.append((a, b))
pu, ar = puentes_y_articulaciones(n, aristas)
clave = lambda a, b: frozenset((a, b))
veces = {}
for a, b in aristas:
veces[clave(a, b)] = veces.get(clave(a, b), 0) + 1
mios = {clave(*aristas[i]) for i in pu}
G = nx.Graph(aristas)
G.add_nodes_from(range(n))
ref = {clave(a, b) for a, b in nx.bridges(G) if veces[clave(a, b)] == 1} # networkx ve el grafo simple; una arista doble no es puente
desacuerdos += mios != ref or set(ar) != set(nx.articulation_points(G))
print("desacuerdos con networkx en 400 grafos (con aristas repetidas):", desacuerdos)The cell reproduces the figure’s three bridges and four articulation points, and agrees with networkx on random graphs including parallel edges (a duplicated edge is not a bridge, so the comparison excludes those appearing more than once). Skipping only the arrival edge, not every edge to the parent, achieves this.
Sixth cell: actual cost. First, memory for a real graph of vertices and edges in Python lists and CSR; then time to build CSR, perform DFS and run Tarjan as edge count grows.
import struct
n, m = 20000, 200000
r = np.random.default_rng(0)
pares = list(zip(r.integers(0, n, m).tolist(), r.integers(0, n, m).tolist()))
listas = [[] for _ in range(n)]
for u, v in pares:
listas[u].append(v)
en_listas = sys.getsizeof(listas) + sum(sys.getsizeof(l) for l in listas) + sum(sys.getsizeof(v) for l in listas for v in l)
en_csr = CSR(n, pares).bytes_numpy()
print(f"puntero de este intérprete: {8 * struct.calcsize('P')} bits")
print(f"listas de Python: {en_listas / 1e6:.2f} MB CSR con int32: {en_csr / 1e6:.2f} MB cociente: {en_listas / en_csr:.1f}")
print(f"\n{'aristas':>9} {'CSR (ms)':>9} {'DFS (ms)':>9} {'Tarjan (ms)':>11} {'µs por arista (Tarjan)':>23}")
for m in (25000, 50000, 100000, 200000):
n = m // 4
r = np.random.default_rng(m)
pares = list(zip(r.integers(0, n, m).tolist(), r.integers(0, n, m).tolist()))
t0 = time.perf_counter(); g = CSR(n, pares)
t1 = time.perf_counter(); dfs(g)
t2 = time.perf_counter(); tarjan(g)
t3 = time.perf_counter()
print(f"{m:9d} {1000 * (t1 - t0):9.1f} {1000 * (t2 - t1):9.1f} {1000 * (t3 - t2):11.1f} {1e6 * (t3 - t2) / m:23.2f}")In 32-bit Pyodide, with smaller pointers and objects, lists occupy 4.92 MB and CSR 0.88 MB, ratio 5.6. On 64-bit CPython, measured outside the browser on the same graph, lists occupied 9.04 MB and the ratio was 10.3, the order of the memory figure’s model. In scaling, Tarjan cost per edge stays around 0.4 µs as edge count grows eightfold (with variation from coarse timing and cache): the proved .
With libraries
For large static graphs none of this needs to be written from scratch. scipy.sparse.csgraph operates on CSR matrices (the same format as above): connected_components(M, directed=True, connection="strong") returns strongly connected components, breadth_first_order and depth_first_order give traversals, all in C. It lacks topological sorting: networkx handles that (topological_sort, topological_generations for waves, condensation, strongly_connected_components, bridges, articulation_points), at the cost of being much slower with dictionaries of dictionaries.
The lab applies the same operations used on toy graphs to a real one: the import graph of a Python package. Read modules of networkx, parse each file with ast and store edge when imports at module level (the edge means, as in the figure, “ must be ready before ”).
import ast
import importlib
import importlib.util
import pkgutil
def listar_modulos(paquete):
"""Todos los módulos y subpaquetes de un paquete instalado: nombre -> es_paquete."""
raiz = importlib.import_module(paquete)
info = {paquete: True}
for m in pkgutil.walk_packages(raiz.__path__, paquete + "."):
info[m.name] = m.ispkg
return info
def fuente(nombre):
return importlib.util.find_spec(nombre).loader.get_source(nombre) or ""
def importados(nombre, es_paquete, conocidos):
"""Módulos del propio paquete que `nombre` importa a nivel de módulo (sin mirar dentro de funciones)."""
base = nombre if es_paquete else nombre.rpartition(".")[0]
pila, destinos = list(ast.parse(fuente(nombre)).body), set()
while pila:
nodo = pila.pop()
if isinstance(nodo, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
if isinstance(nodo, ast.Import):
for a in nodo.names:
partes = a.name.split(".")
for i in range(1, len(partes) + 1): # importar a.b.c ejecuta también a y a.b
destinos.add(".".join(partes[:i]))
elif isinstance(nodo, ast.ImportFrom):
origen = nodo.module or ""
if nodo.level: # import relativo
subir = base.split(".")[: len(base.split(".")) - (nodo.level - 1)]
origen = ".".join(subir + ([origen] if origen else []))
partes = origen.split(".")
for i in range(1, len(partes) + 1):
destinos.add(".".join(partes[:i]))
for a in nodo.names: # from p import m puede importar el módulo p.m
destinos.add(origen + "." + a.name)
pila.extend(ast.iter_child_nodes(nodo))
destinos.discard(nombre)
return destinos & conocidos
t0 = time.perf_counter()
info = listar_modulos("networkx")
nombres = sorted(m for m in info if ".tests" not in m) # sin los módulos de pruebas
indice = {m: i for i, m in enumerate(nombres)}
conocidos = set(nombres)
pares = sorted({(indice[d], indice[m]) for m in nombres for d in importados(m, info[m], conocidos)})
t1 = time.perf_counter()
print(f"{len(nombres)} módulos, {len(pares)} aristas de importación (leído y analizado en {t1 - t0:.1f} s)")Second practice cell: components and ordering with all three implementations, with a surprise about the graph itself.
from scipy.sparse.csgraph import breadth_first_order, depth_first_order
n_mod = len(nombres)
g = CSR(n_mod, pares)
M = csr_matrix((np.ones(len(pares), dtype=np.int8), ([a for a, _ in pares], [b for _, b in pares])), shape=(n_mod, n_mod))
print("el CSR de scipy tiene los mismos indptr e indices (como conjuntos por fila):",
list(M.indptr) == g.indptr and all(set(M.indices[M.indptr[u]:M.indptr[u + 1]]) == set(g.vecinos(u)) for u in range(n_mod)))
t0 = time.perf_counter(); comp, nc = tarjan(g)
t1 = time.perf_counter(); nc_s, lab_s = connected_components(M, directed=True, connection="strong")
t2 = time.perf_counter(); G = nx.DiGraph(pares); nc_x = len(list(nx.strongly_connected_components(G)))
t3 = time.perf_counter()
tam = np.bincount(comp)
print(f"componentes fuertemente conexas: Tarjan {nc}, scipy {nc_s}, networkx {nc_x}; mayor componente: {tam.max()} módulos")
print(f"tiempos: propio {1000 * (t1 - t0):.2f} ms, scipy {1000 * (t2 - t1):.2f} ms, networkx (con construir el grafo) {1000 * (t3 - t2):.2f} ms")
# la sorpresa: un ciclo gigante que viene del mecanismo de los paquetes. Quitando las aristas hacia paquetes ascendientes
# (el «import networkx as nx» de un submódulo, que solo se usa en tiempo de ejecución), el grafo se queda sin ciclos.
def es_ascendiente(a, b):
return nombres[b].startswith(nombres[a] + ".")
sin_asc = [(a, b) for a, b in pares if not es_ascendiente(a, b)]
g2 = CSR(n_mod, sin_asc)
orden, _ = kahn(g2)
print(f"sin aristas hacia ascendientes: {len(sin_asc)} aristas, Kahn coloca {len(orden)} de {n_mod} módulos")
G2 = nx.DiGraph(sin_asc)
G2.add_nodes_from(range(n_mod))
olas = list(nx.topological_generations(G2))
print(f"orden válido: {verificar_orden(g2, orden)}; olas de compilación (camino crítico + 1): {len(olas)}, la más ancha tiene {max(map(len, olas))} módulos")
print("primeros módulos del orden:", [nombres[v] for v in orden[:4]])
# recorridos de scipy contra los propios
alc_scipy = set(breadth_first_order(M, 0, directed=True, return_predecessors=False))
alc_mio = {v for v, dv in enumerate(bfs(g, 0)) if dv >= 0}
alc_dfs = set(depth_first_order(M, 0, directed=True, return_predecessors=False))
print("alcanzables desde el paquete raíz: BFS de scipy == BFS propia:", alc_scipy == alc_mio, "; DFS de scipy == BFS propia:", alc_dfs == alc_mio, f"({len(alc_mio)} módulos)")Three lessons from practice. First, scipy’s CSR is the one built by hand: indptr and indices are the same arrays (rows possibly in a different order), so csgraph routines can consume what was implemented here. Second, Python package structure itself creates a giant cycle: in the version of networkx loaded by Pyodide, 277 of 287 modules lie in one strongly connected component. This is because import networkx as nx inside a submodule is an edge to the root package, and the package’s __init__ imports every submodule. It is a “harmless” cycle (import is used at execution, not load time), and removing edges to ancestor packages makes the graph acyclic with a ten-wave compilation order, the widest containing 118 modules that could run in parallel. Third, timing: in this run scipy is the fastest implementation and networkx the slowest (also including graph construction), though with only a few hundred vertices all take milliseconds or less and the difference matters for millions of edges, not here.
Common mistakes
Exercises
Step 1 of 4. (, by contrapositive) Suppose there is a back edge . How do you obtain a cycle?
Step 1 of 4. Reasoning by contradiction, what do you assume?
componentes(n, aristas): receive a vertex count and directed edges (u, v) (loops and repeated edges are allowed) and return a list comp of length n with each vertex's strongly connected component number. Numbering must be reverse topological: every edge u -> v must satisfy comp[u] >= comp[v], and components must use numbers 0, 1, 2, ... without gaps. It must be iterative: tests include a path and a ring of 100000 vertices that would overflow Python recursion.def componentes(n, aristas):
"""comp[v] = número de la componente fuertemente conexa de v, con comp[u] >= comp[v] para toda arista u -> v."""
return [] # tu códigoordenar(n, aristas): return ('orden', lista) with a topological order of the n vertices if the directed graph is acyclic, or ('ciclo', lista) with a cycle otherwise. A cycle is a vertex list [v0, v1, ..., vk] with edges v0 -> v1, v1 -> v2, ..., vk -> v0 (a loop v -> v is cycle [v]). It must be iterative: tests include a path of 100000 vertices.def ordenar(n, aristas):
"""('orden', lista) si el grafo es acíclico; ('ciclo', lista) con un ciclo si no."""
return ("orden", []) # tu códigoMore than one answer may be correct.
More than one answer may be correct.
indptr array of integers and an indices array of integers. How many bytes total?int object, distinct per edge). How many times as much memory does it use as the previous exercise's 32-bit CSR? Answer to two decimals.Summary
- Representation. Matrix , lists , CSR compact and static; choose by density and operations. Build CSR by counting sort; it is the format of
scipy.sparse. - BFS with
dequegives edge distances in ; withlist.pop(0)it becomes quadratic. - DFS. Times and ; parenthesis theorem (disjoint or nested intervals) and white-path theorem; tree, back, forward and cross edges by destination color; undirected graphs have only tree and back edges.
- Topological order. Exists iff the graph is acyclic. Kahn (in-degrees, waves, cycle certificate from remaining vertices) and DFS (decreasing ; a back edge gives a cycle). Both return verifiable certificates.
- Strong components. The condensation is a DAG. Kosaraju: two DFS traversals and the transpose, with the lemma that inter-component edges decrease in . Tarjan: one pass with stack and ; a component closes when , numbered in reverse topological order. Applications: 2-SAT, mutual recursion, dependency analysis.
- Bridges and articulation points. is a bridge iff ; a vertex is an articulation point if a child satisfies , or it is a root with two children. Always use iteration and skip the arrival edge by ID.
These traversals underpin what follows. Shortest paths in a DAG from the shortest-path lesson are dynamic programming in topological order (the same structure as subproblems as a DAG), and Dijkstra and maximum-flow algorithms reuse BFS and DFS with other data structures. In Datalog with stratified negation rule evaluation follows a topological order of dependency-graph components, and backpropagation engines traverse the computation graph in reverse topological order.