Teoría de grafos, paso a paso

Curso gratuito
Primero, el cuestionario del capítulo 1

Primero, repasa el capítulo 1

Haz el cuestionario del capítulo 1: 10 preguntas, se aprueba con 7 correctas. Puedes repetirlo cuantas veces quieras.

One-Way Streets

Capítulo 2, lección 4 de 4

Strongly connected components: the groups of places you can always get back from.

Narrado en inglés. Activa arriba los subtítulos en inglés, árabe, alemán, español o francés.

Lección escrita

8 min de lecturaEscrita en inglés.

Picture a town where every street is one way. From the station you can drive to the harbour, but once you are there, there is no way back. In a directed graph, getting somewhere and getting back are two different questions. The places you can always return from form groups called strongly connected components.

One or two depth-first searches are enough to find them all, and they show how a whole network is put together. This lesson covers what these components are, why they always form a DAG, two algorithms that find them and why they work, and how to make every street one way without trapping anyone.

Reaching and returning

In a directed graph, a vertex u reaches a vertex v when a path of arrows leads from u to v. Two vertices are strongly connected when each one reaches the other.

A strongly connected component is a largest possible group in which every pair is strongly connected. "Largest" matters: in a triangle A → B → C → A, the pair A, B is strongly connected, but it is not a component, because C can join it.

Mutual reaching behaves like equality: every vertex reaches itself, it works in both directions, and two paths can be joined end to end. So the components split the vertices into groups that never overlap; every vertex belongs to exactly one.

Here is the example from our guide: nine vertices and twelve arrows.

FromABCDEFGHI
Arrows toBC, FDECA, GHD, G, Inone

It has four components: the triangle A, B, F, the triangle C, D, E, the pair G, H, and I on its own, because I lies on no cycle.

Nine vertices, twelve arrows, four strongly connected components.Nine vertices, twelve arrows, four strongly connected components.

Ignore the directions and the whole graph is in one piece; that is called weak connectivity. Strong connectivity asks for more: from I, you cannot get anywhere at all.

A DAG of components

Now shrink each component to a single point, and draw an arrow between two components whenever some arrow joins them. This is called the condensation. Here it has four points and four arrows: A B F → C D E, A B F → G H, G H → C D E and G H → I.

The condensation of every directed graph is a DAG.

Why. If the components formed a cycle, you could travel around it, so every vertex in all of them would reach every other one, and they would be one big component. They were never separate at all.

So every directed graph, however tangled, is a DAG whose points hide cycles. As in the last lesson, it has a topological order: A, B, F first, then G and H, then I and C, D, E.

The condensation: each component shrunk to a point, and the result is a DAG.The condensation: each component shrunk to a point, and the result is a DAG.

The condensation answers questions at a glance:

  • Who can reach everyone? Only A, B and F, because theirs is the only component with nothing coming in (a source).
  • How many new arrows make the whole graph strongly connected? Two, because the condensation has one source and two dead ends (sinks), C D E and I. In general you need the larger of the two counts, unless the graph is already one component.

Kosaraju: two passes

Searching again from every vertex would work, but it repeats a lot of effort. Kosaraju's algorithm needs just two depth-first searches.

  1. Pass one. Search the whole graph and write down the order in which the vertices finish: E, D, C, I, H, G, F, B, A.
  2. Reverse every arrow. Two vertices that reach each other still do, so the components stay exactly the same.
  3. Pass two. Take the vertices from the last to finish to the first, and search the reversed graph from each one not used yet. From A the search finds A, F and B, and stops. From G it finds G and H. Then I alone, and finally C, E and D.

Pass two searches the reversed graph, starting from the last vertex to finish.Pass two searches the reversed graph, starting from the last vertex to finish.

Why it never spills over. The vertex that finishes last always lies in a source component, one with nothing pointing into it. Reversed, nothing points out of it, so the search from there is trapped inside exactly that component. Set it aside, and the same holds for the next one.

The order matters. Start from the first vertex to finish instead, and the search from E leaks through almost everything, returning eight vertices as one false component.

Tarjan: one pass

Tarjan's algorithm needs only one search. It numbers the vertices in the order it discovers them, keeps the unfinished ones on a stack, and gives each vertex a second number, its low number: the earliest vertex still on the stack that it can climb back to.

  1. Start at A and dive: A, B, C, D, E. The arrow from E back to C lowers E's low number to C's, and that passes back up through D to C.
  2. When C finishes, nothing below it climbed any higher than C itself, so C is the root of a component. Pop the stack down to C: that gives C, D, E.
  3. Back at B, the search visits F, whose arrow to A lowers it to A's number. Then G, H and I. The arrow from H to D is ignored, because D's component is already finished and off the stack.
  4. I finishes alone, so it is a component by itself. Then G finishes as the root of G, H, and finally A as the root of A, B, F.

Tarjan's algorithm: discovery numbers, low numbers and the stack.Tarjan's algorithm: discovery numbers, low numbers and the stack.

That check, whether a vertex is still on the stack, is the one people forget. Without it, the arrow from H to D drags H's low number down, G never sees itself as a root, and G and H are wrongly merged with A, B and F, although H cannot reach A.

Both algorithms touch every vertex and arrow a constant number of times, so both run in linear time, O(n + m). Kosaraju reports the components from sources to sinks; Tarjan reports them sinks first.

Making streets one way

Back to the town. The council wants to make every street one way. When can that be done so that everyone can still drive from anywhere to anywhere?

Herbert Robbins answered this in 1939:

A street map can be made one way, with every place still reachable from every other, exactly when it is connected and has no bridge.

A bridge is clearly fatal. Whichever way it points, you can cross it in one direction only and never come back.

Without bridges, depth-first search builds the answer. Point each street it follows away from the start (down the search tree), and every other street back up the tree, from the later corner to the earlier one.

Tree streets point down, all other streets point back up.Tree streets point down, all other streets point back up.

Why it works. From the start you can reach every corner by going down the tree. And because no street is a bridge, every part of the search tree has some street leading back above it, so from any corner you can climb back up, step by step, to the start. Everyone can reach the start and the start can reach everyone: the whole town is one strongly connected component.

In the world

The web is a directed graph of pages and links. A study in 2000 mapped about two hundred million pages and found a bow tie: one giant component at the centre, pages that lead into it on one side, and pages you can reach from it but never leave on the other.

The same idea finds deadlocks, where programs wait for each other in a circle, and it solves whole families of either-or scheduling puzzles (known as 2-SAT) in linear time.

In Python, Kosaraju's algorithm fits in two dozen lines: one search to record the finishing order, one pass to reverse the arrows, and one more search for each component.

def kosaraju(adj):
    order, seen = [], set()

    def visit(u):
        seen.add(u)
        for v in adj[u]:
            if v not in seen:
                visit(v)
        order.append(u)  # u finishes

    for u in adj:
        if u not in seen:
            visit(u)

    radj = {u: [] for u in adj}  # reverse every arrow
    for u in adj:
        for v in adj[u]:
            radj[v].append(u)

    comps, done = [], set()
    for u in reversed(order):  # last to finish first
        if u in done:
            continue
        comp, stack = [], [u]
        done.add(u)
        while stack:
            x = stack.pop()
            comp.append(x)
            for y in radj[x]:
                if y not in done:
                    done.add(y)
                    stack.append(y)
        comps.append(comp)
    return comps

adj = {"A": ["B"], "B": ["C", "F"], "C": ["D"], "D": ["E"], "E": ["C"],
       "F": ["A", "G"], "G": ["H"], "H": ["D", "G", "I"], "I": []}
kosaraju(adj)  # [['A', 'F', 'B'], ['G', 'H'], ['I'], ['C', 'E', 'D']]

Kosaraju's algorithm in Python.Kosaraju's algorithm in Python.

Key ideas

  • Two vertices are strongly connected when each can reach the other, and the strongly connected components split every directed graph into separate groups.
  • Shrinking each component to a point always leaves a DAG, the condensation.
  • Kosaraju finds the components with two searches, the second on the reversed graph. Tarjan uses one search, a stack and low numbers. Both run in linear time.
  • A town can make every street one way without trapping anyone exactly when its street map is connected and has no bridge.

Check yourself

1. Add the arrow I → A to the example. What are the strongly connected components now?

2. A directed graph has a condensation with 3 sources and 5 sinks. What is the smallest number of arrows you must add to make it strongly connected?

3. A town's street map is a single long road with houses along it. Can its streets be made one way without trapping anyone?

Practice on the platform

The strongly connected components guide traces all of this on the same example, including the bugs that slip through small tests. In the Tarjan visualizer, import the example as a directed list and run it: four components, exactly the ones we found by hand. The Kosaraju visualizer runs the two-pass version.

A continuación

Contenido del curso

0 de 20 vistas

Capítulo 1Graph Theory Foundations

Capítulo 2Exploring a GraphPrimero, el cuestionario del capítulo 1

Capítulo 3Shortest PathsPrimero, el cuestionario del capítulo 2

Capítulo 4Connecting CheaplyPrimero, el cuestionario del capítulo 3

Capítulo 5Hard ProblemsPrimero, el cuestionario del capítulo 4

Capítulo 6Network FlowsPrimero, el cuestionario del capítulo 5