ENع
→Strong components
الدرس 25 · Graph algorithms

Strongly connected components

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة11 خطوة5 أسئلةIntermediate
عن هذا الدرس

In a graph with one-way arrows, some nodes can reach each other both ways and some cannot. A strongly connected component is a largest group of nodes that can all reach each other. Kosaraju's algorithm finds every component with two depth-first searches: one to record the order nodes finish in, and one on the graph with every arrow reversed. Watch it run on six nodes, step by step. The Software lessons "Graphs" and "Graph search: BFS and DFS" and the Maths lesson "Graph theory: vertices, edges and breadth-first search" cover the graph basics and depth-first search used here. Union-find groups nodes when edges go both ways; this lesson handles one-way arrows.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 25 · تفاعلي
01 / 11

A map of one-way arrows

A directed graph has nodes joined by one-way arrows. In Python we store it as a dict: each node lists the nodes its arrows point to. This one has six nodes and seven arrows.

g = {
  'A': ['B'],
  'B': ['A', 'C'],
  'C': ['D'],
  'D': ['E'],
  'E': ['C'],
  'F': ['E'],
}

6 nodes, 7 arrows: A→B  B→A  B→C  C→D  D→E  E→C  F→E
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A map of one-way arrows

    A directed graph has nodes joined by one-way arrows. In Python we store it as a dict: each node lists the nodes its arrows point to. This one has six nodes and seven arrows.

    g = {
      'A': ['B'],
      'B': ['A', 'C'],
      'C': ['D'],
      'D': ['E'],
      'E': ['C'],
      'F': ['E'],
    }
    
    6 nodes, 7 arrows: A→B  B→A  B→C  C→D  D→E  E→C  F→E
  2. Nodes that reach each other

    Two nodes are strongly connected when each can reach the other along arrows. C, D and E sit on a loop, so all three are. A strongly connected component (SCC) is a largest group like that.

    u and v are strongly connected when
      there is a path u → … → v  and  a path v → … → u
    
    C → D → E → C   one loop: C, D, E reach each other
    A → B → A       A and B reach each other
    F → E           but no path from E back to F
    
    every node is in exactly one SCC
  3. Pass 1: search from A

    Pass 1 is a depth-first search (DFS): follow an arrow to a new node, go as deep as you can, and back up only when stuck. From A it goes A, B, C, D, E. E only points at C, already seen.

    pass 1: order = finish_order(g)
    
    start at A
      A → B   new, go deeper
      B → A   A already seen, skip
      B → C   new, go deeper
      C → D   new, go deeper
      D → E   new, go deeper
      E → C   C already seen, skip
  4. Finished nodes join a list

    A node is finished when every arrow out of it has been tried. E finishes first. Backing up, D, C, B and A finish in turn. Each one joins the end of the order list as it finishes.

    finish = every arrow out of the node has been tried
    
      E finished   order = [E]
      D finished   order = [E, D]
      C finished   order = [E, D, C]
      B finished   order = [E, D, C, B]
      A finished   order = [E, D, C, B, A]
  5. F starts a second search

    No arrow led to F, so the loop over all nodes starts a new search there. F's arrow points at E, already seen, so F finishes at once. The order list is now E, D, C, B, A, F.

    for v in g: if v not in seen: dfs(v)
      A, B, C, D, E already seen
      F not seen: start again at F
      F → E   E already seen, skip
      F finished
    
    order = ['E', 'D', 'C', 'B', 'A', 'F']
    F finished last
  6. Why not search from F?

    A search finds everything a node can reach. Searching from F on these arrows reaches F, E, C, D. But E cannot reach F, so that search mixes two components. We need searches that cannot leak out.

    walk(g, 'F') on the original arrows
      reaches F, E, C, D
    
    F → E but no path E → … → F
    so F and E are in different SCCs:
    a plain search spills into C, D, E
  7. Flip every arrow

    So reverse every arrow. Components stay the same, since a loop reversed is still a loop. F finished last, so no arrow came into its group. Flipped, no arrow leaves it: a search from F is trapped.

    rg = reverse(g)
      rg['A'] = ['B']
      rg['B'] = ['A']
      rg['C'] = ['B', 'E']
      rg['D'] = ['C']
      rg['E'] = ['D', 'F']
      rg['F'] = []
    
    the node that finishes last lies in a group
    no outside arrow enters (CLRS, ch. 20)
  8. Pass 2: F alone

    Pass 2 reads the order list from the end, so F goes first. Searching the flipped arrows, F has nowhere to go. The search finds only F: that is the first component.

    for v in reversed(order):
      reversed(order) = F, A, B, C, D, E
    
    v = F   walk(rg, 'F') finds [F]
    comps = [[F]]
  9. A and B together

    Next comes A. Its flipped arrow reaches B, and B can only go back to A. The arrow from C now points into B, not out. So the search stops: A and B form the second component.

    v = A   walk(rg, 'A')
      A → B   new
      B → A   already seen
      finds [A, B]
    comps = [['F'], ['A', 'B']]
  10. The loop C, D, E

    B is already in a component, so skip it. C starts the last search: it reaches E, then E reaches D. The arrows toward B and F lead to nodes already taken. Third component: C, E, D.

    v = B   already seen, skip
    v = C   walk(rg, 'C')
      C → B   already seen
      C → E   new
      E → D   new
      D → C   already seen
      E → F   already seen
      finds [C, E, D]
    v = D, v = E   already seen
    
    scc(g) = [['F'], ['A', 'B'], ['C', 'E', 'D']]
  11. Two searches, linear time

    Each pass visits every node once and tries every arrow once, and flipping touches each arrow once. With V nodes and E arrows the total work is O(V + E), the same as a single search.

    pass 1     O(V + E)
    reverse    O(V + E)
    pass 2     O(V + E)
    total      O(V + E)
    
    here V = 6, E = 7
    result: [['F'], ['A', 'B'], ['C', 'E', 'D']]
    
    ;; the full program (Python 3, runs as-is)
    def finish_order(g):
        order, seen = [], set()
        def dfs(v):
            seen.add(v)
            for w in g[v]:
                if w not in seen:
                    dfs(w)
            order.append(v)  # v is finished
        for v in g:
            if v not in seen:
                dfs(v)
        return order
    
    def reverse(g):
        rg = {v: [] for v in g}
        for v in g:
            for w in g[v]:
                rg[w].append(v)
        return rg
    
    def walk(g, v, seen):
        seen.add(v)
        found = [v]
        for w in g[v]:
            if w not in seen:
                found += walk(g, w, seen)
        return found
    
    def scc(g):
        order = finish_order(g)
        rg = reverse(g)
        seen, comps = set(), []
        for v in reversed(order):
            if v not in seen:
                c = walk(rg, v, seen)
                comps.append(c)
        return comps
    
    g = {'A': ['B'], 'B': ['A', 'C'], 'C': ['D'],
         'D': ['E'], 'E': ['C'], 'F': ['E']}
    print(finish_order(g))
    print(scc(g))
    

اختبار يتاح بعد الخطوة الأخيرة.