topologicalOrdering property

Set<T>? topologicalOrdering
inherited

Returns a set containing all graph vertices in topological order.

  • For every directed edge: (vertex1 -> vertex2), vertex1 is listed before vertex2.

  • Note: There is no topological ordering if the graph is cyclic. In that case the function returns null.

  • Any self-loop (e.g. vertex1 -> vertex1) renders a directed graph cyclic.

  • Based on a depth-first search algorithm (Cormen 2001, Tarjan 1976).

Implementation

Set<T>? get topologicalOrdering {
  final queue = Queue<T>();
  final perm = HashSet<T>();
  final temp = HashSet<T>();

  // Marks graph as cyclic.
  var isCyclic = false;

  // Recursive function
  void visit(T vertex) {
    // Graph is not a Directed Acyclic Graph (DAG).
    // Terminate iteration.
    if (isCyclic) return;

    // Vertex has permanent mark.
    // => This vertex and its neighbouring vertices
    // have already been visited.
    if (perm.contains(vertex)) return;

    // A cycle has been detected. Mark graph as acyclic.
    if (temp.contains(vertex)) {
      isCyclic = true;
      return;
    }

    // Temporary mark. Marks current vertex as visited.
    temp.add(vertex);
    for (final connectedVertex in edges(vertex)) {
      visit(connectedVertex);
    }
    // Permanent mark, indicating that there is no path from
    // neighbouring vertices back to the current vertex.
    // We tried all options.
    perm.add(vertex);
    queue.addFirst(vertex);
  }

  // Main loop
  // Note: Iterating in reverse order of [vertices]
  // (approximately) preserves the
  // sorting of vertices (on top of the topological sorting.)
  // For a sorted topological ordering use
  // the getter: [sortedTopologicalOrdering].
  //
  // Iterating in normal order of [vertices] yields a different
  // valid topological sorting.
  for (final vertex in sortedVertices.toList().reversed) {
    visit(vertex);
    if (isCyclic) break;
  }

  // Return null if graph is not a DAG.
  return (isCyclic) ? null : queue.toSet();
}