Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

Topological Order #258

Open Qingquan-Li opened 9 months ago

Qingquan-Li commented 9 months ago

In college, before taking a particular course, students, usually, must take all its prerequisite courses, if any. For example, before taking the Programming II course, the student must take the Programming I course. However, certain courses can be taken independently of each other. The courses within a department can be represented as a directed graph. A directed edge from, say vertex u to vertex v means the course represented by the vertex u is a prerequisite of the course represented by the vertex v. The Topological Order algorithm can be used to output the vertices of a directed graph in such a sequence.

Topological Ordering

Definition

Topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex U to vertex V, U comes before V in the ordering.

Properties

Example 1

A --> B
|     |
v     v
C --> D

Possible Topological Orderings for this directed acyclic graph:

  1. A, B, C, D
  2. A, C, B, D

Both are valid as they satisfy the rule that for every directed edge UV, U comes before V in the ordering.

Example 2

   B
  ^ \
 /   v
A --> C --> D

Possible Topological Orderings for this directed acyclic graph:

  1. A, B, C, D
  2. A, C, B, D

Both are valid as they satisfy the rule that for every directed edge UV, U comes before V in the ordering.

Applications

Algorithms

Depth-First Search versus Breadth-First Search

DFS-BFS

(source: https://medium.com/basecs/breaking-down-breadth-first-search-cebe696709d9)

Breadth-First Topological Ordering

Definition

It's a variant of topological sorting where Breadth-First Search (BFS) is used instead of DFS. This approach uses the concept of in-degree of nodes.

Algorithm (Kahn's Algorithm)

Properties

Applications

Same as general topological sorting but more efficient in certain scenarios, especially in distributed systems or parallel computing environments.