In a directed graph the edges have a direction, and DFS reveals cycles and gives a valid order for scheduling tasks.

DFS on a Directed Graph

The same DFS procedure applies, following edges only in their direction. Edges are classified: tree edges (to an unvisited vertex), back edges (to an ancestor still being processed, which are exactly the edges that close a cycle), forward edges (to a descendant already finished) and cross edges (to a finished vertex in another branch). A directed graph has a cycle if and only if DFS finds a back edge. Vertices are coloured white (unvisited), grey (in progress, on the stack) and black (finished); an edge into a grey vertex is a back edge. The time remains Θ(V + E).

Directed Acyclic Graphs

A directed acyclic graph (DAG) is a directed graph with no cycle. DAGs model dependencies: course prerequisites, build steps in software, tasks in a project, spreadsheet cell formulas. If the dependencies contain a cycle, the tasks can never all be done.

Topological Sorting

A topological ordering of a DAG lists all vertices so that for every edge u → v, u comes before v. It exists only for a DAG and is usually not unique. DFS method: run DFS on the whole graph; when a vertex finishes, put it at the front of a list (or push it on a stack); the final list is a topological order, i.e. vertices sorted by decreasing finish time. Kahn's method: compute the in-degree of every vertex, place vertices of in-degree 0 in a queue; repeatedly remove one, output it and reduce the in-degree of its successors, adding those that reach 0; if fewer than V vertices are output, a cycle exists. Both take Θ(V + E).

Definition: Topological sort. A linear ordering of the vertices of a directed acyclic graph in which every edge goes from an earlier vertex to a later one.

Table 3.7: Directed graph terms

Term Meaning Use
Back edge Edge to a vertex still on the stack Detects a cycle
DAG Directed graph with no cycle Models dependencies
In-degree Number of incoming edges Kahn's algorithm
Finish time Time DFS leaves a vertex Topological order by decreasing value

Example 3.7: Ordering courses

Problem: Prerequisites: Maths → DS, Prog → DS, DS → DAA, DAA → AI, Prog → Web. Give a valid order.

Solution:

  1. In-degrees: Maths 0, Prog 0, DS 2, DAA 1, AI 1, Web 1.
  2. Start queue [Maths, Prog]. Remove Maths: DS in-degree becomes 1.
  3. Remove Prog: DS becomes 0 and Web becomes 0; queue [DS, Web].
  4. Remove DS: DAA becomes 0. Remove Web. Remove DAA: AI becomes 0. Remove AI.

Result: One valid order is Maths, Prog, DS, Web, DAA, AI; all 6 vertices are output, so there is no cycle.

from collections import deque
g = {"Maths": ["DS"], "Prog": ["DS", "Web"], "DS": ["DAA"],
     "DAA": ["AI"], "AI": [], "Web": []}
indeg = {v: 0 for v in g}
for u in g:
    for v in g[u]:
        indeg[v] += 1
q = deque(v for v in g if indeg[v] == 0)
order = []
while q:
    u = q.popleft()
    order.append(u)
    for v in g[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            q.append(v)
print(order, "cycle" if len(order) < len(g) else "no cycle")

Output

['Maths', 'Prog', 'DS', 'Web', 'DAA', 'AI'] no cycle

Common mistakes

  • Attempting a topological sort of a graph that has a cycle.
  • Treating any edge to a visited vertex as a cycle in a directed graph; only back edges count.
  • Expecting a unique topological order.
  • Ordering by increasing finish time instead of decreasing.

Key takeaways

  • A directed graph has a cycle exactly when DFS finds a back edge.
  • Topological order exists only for a DAG; every edge goes forward.
  • DFS method: order by decreasing finish time; Kahn: repeatedly remove in-degree 0 vertices.
  • Both run in Θ(V + E).

Practice questions

  1. What is a topological ordering?
  2. How does DFS detect a cycle in a directed graph?
  3. Name the two methods for topological sorting.

Answers to the practice questions

  1. A linear order of a DAG's vertices in which for every edge u → v, u precedes v.
  2. By finding a back edge to a vertex still on the recursion stack.
  3. DFS by decreasing finish time, and Kahn's in-degree method.

Sources

  • Official BCA syllabus Design and Analysis of Algorithms, course code 26BCA404DS03, Unit III