ENع
→DFS times and cycles
الدرس 21 · Graph algorithms

DFS in depth: discovery times and cycle detection

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

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Depth-first search becomes far more useful once it carries a clock. Run it on a small directed graph and stamp each node twice: when its call starts (discovery) and when it ends (finish). The stamps show which calls are still open, sort every edge into tree, back, forward or cross, and give a clean test for cycles: a directed graph has one exactly when DFS finds a back edge. The Software lessons "Graphs" and "Graph search: BFS and DFS" and the Maths lesson on graph theory introduce the graphs and the plain search used here.

ستتعلّم

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

شكل 21 · تفاعلي
01 / 10

A directed graph

Each edge here is one-way: A→B lets you go from A to B, not back. Five nodes, six edges. Depth-first search (DFS) follows edges as deep as it can, then backs up. We will time every move it makes.

adj = {
    "A": ["B", "D"],
    "B": ["C"],
    "C": ["A", "D"],
    "D": [],
    "E": ["C"],
}
>>> adj["C"]      # C's edges lead to A and D
['A', 'D']
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A directed graph

    Each edge here is one-way: A→B lets you go from A to B, not back. Five nodes, six edges. Depth-first search (DFS) follows edges as deep as it can, then backs up. We will time every move it makes.

    adj = {
        "A": ["B", "D"],
        "B": ["C"],
        "C": ["A", "D"],
        "D": [],
        "E": ["C"],
    }
    >>> adj["C"]      # C's edges lead to A and D
    ['A', 'D']
  2. Discover A at time 1

    A clock counts up by 1 at every start and every end. visit(A) runs first and stamps A's discovery time: d[A] = 1. A turns gray, meaning found but not finished. Its call waits on the call stack.

    clock = count(1)        # 1, 2, 3, ...
    visit("A")
        d["A"] = next(clock)    # 1
    
    colour = white  if u not in d
             gray   if u in d but not in f
             black  if u in f
    
    call stack: visit(A)
  3. Dive deeper: B, then C

    A's first edge leads to B. B is white, never seen, so visit(B) starts: d[B] = 2. B→C works the same way: d[C] = 3. These are tree edges. The gray nodes A, B and C are exactly the call stack.

    A→B  B is white  → tree edge, visit(B)
        d["B"] = 2
    B→C  C is white  → tree edge, visit(C)
        d["C"] = 3
    
    call stack: visit(A) visit(B) visit(C)
    gray: A B C
  4. C→A is a back edge

    C looks along its edge to A. A is gray: its call is still on the stack, so A is an ancestor of C. An edge back to an ancestor closes a loop, A→B→C→A. That is a cycle, and the lamp turns on.

    C→A  "A" in d    → seen
         "A" not in f → still open: gray
         back.append(("C", "A"))
    
    path on the stack: A → B → C
    plus the edge C → A: a cycle A→B→C→A
    >>> back
    [('C', 'A')]
  5. D finishes first

    C's next edge leads to D, which is white: another tree edge, d[D] = 4. D has no edges going out, so its call ends at once: f[D] = 5, its finish time. D turns black, done for good.

    C→D  D is white  → tree edge, visit(D)
        d["D"] = 4
        for v in adj["D"]:   # [] : nothing to do
        f["D"] = next(clock) # 5
    
    call stack: visit(A) visit(B) visit(C)
    black: D
  6. Back up: C, then B

    With D done, C has no edges left, so C finishes at 6 and its call leaves the stack. B had only one edge, so B finishes at 7. Calls finish in the reverse order they started.

    f["C"] = 6     visit(C) returns
    f["B"] = 7     visit(B) returns
    
    call stack: visit(A)
    black: D C B   (finish order so far)
  7. A→D is a forward edge

    Back in A, the next edge leads to D. D is black, and d[A] = 1 is less than d[D] = 4: D was found inside A's call, so D is a descendant. A forward edge, no loop. A finishes at 8.

    A→D  "D" in f    → black: nothing to do
         d["A"] = 1 < d["D"] = 4
         → D is a descendant of A: forward edge
    f["A"] = 8     visit(A) returns
    
    call stack: (empty)
  8. E→C is a cross edge

    The outer loop finds E still white, so a new search starts there: d[E] = 9. E→C points at black C, and d[C] = 3 is less than 9: C finished before E began. A cross edge. f[E] = 10.

    for u in adj:            # A B C D done
        visit("E")           # d["E"] = 9
    E→C  "C" in f    → black
         d["E"] = 9 > d["C"] = 3
         → C finished before E began: cross edge
    f["E"] = 10
  9. Times nest like brackets

    Write ( at each discovery and ) at each finish: (A (B (C (D D) C) B) A) (E E). D's span, 4 to 5, sits inside C's 3 to 6, inside B's, inside A's. Spans nest or stay apart, never half-overlap.

    >>> d
    {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 9}
    >>> f
    {'D': 5, 'C': 6, 'B': 7, 'A': 8, 'E': 10}
    
    (A (B (C (D D) C) B) A) (E E)
    
    v is a descendant of u
      ⇔  d[u] < d[v] < f[v] < f[u]
  10. A cycle means a back edge

    A directed graph has a cycle exactly when DFS finds a back edge. Delete C→A and run again: every time stays the same, but no edge reaches a gray node, so the lamp stays 0. Cost: O(V + E).

    adj["C"] = ["D"]          # C→A deleted
    >>> back
    []                        # no back edge: no cycle
    
    each node: entered once, left once
    each edge: looked at once
    V + E = 5 + 6: time O(V + E)

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