Ancestors

Finds every vertex that can reach a vertex, such as all the courses one course needs first.

Time complexity O(V+E), gograph function dag.Ancestors.

How it works

Ancestors runs the same search backward. It follows edges in reverse from a vertex and collects every vertex that can reach it. With an edge from A to B read as B depending on A, these are everything the vertex depends on, directly or through others.

A gograph graph doesn't index incoming edges, so dag.Ancestors first reads every edge once to find them, then searches breadth first. It costs O(V+E) and returns the vertices nearest first. The vertex itself is in the result only when it's on a cycle.

Use it to find what has to finish before a job can start, which courses come before another, or why a module is in a build. In go mod graph, an edge goes from a module to one it requires, so the ancestors of a module are the modules that pull it in.

Course prerequisites

Fourteen courses of a computer science degree, each one semester long. Each edge points from a course to a course that requires it.

A directed graph with 14 vertices and 18 edges.

Which courses must a student pass before taking Compilers?

6 vertices can reach Compilers: Algorithms, Computer systems, Data structures, Discrete math, Programming 1 and Programming 2.

Step by step

  1. The graph stores only the edges out of each vertex, so read every edge once, 18 in all, to find the edges into each one.
  2. Start at Compilers. It has edges from Computer systems and Algorithms. Both are new, so they join the queue.
  3. Take Computer systems from the queue. It has an edge from Programming 2, which is new, so it joins the queue.
  4. Take Algorithms from the queue. It has edges from Discrete math and Data structures. Both are new, so they join the queue.
  5. Take Programming 2 from the queue. It has an edge from Programming 1, which is new, so it joins the queue.
  6. Take Discrete math from the queue. It has no edges in.

2 more steps lead to the last one:

  1. Done. 6 vertices can reach Compilers.

Use it in Go

jobs, err := dag.Ancestors(g, "Compilers")
if err != nil {
	return err
}
for _, v := range jobs {
	fmt.Println(v.Label())
}

Example graphs

More in Dependencies

  • Descendants: Finds every vertex reachable from a vertex, such as all the jobs that wait for one step of a build.
  • Affected: Finds the changed vertices and every vertex reachable from them, such as all the cells a spreadsheet edit recomputes.
  • Transitive reduction: Drops every edge that a longer path already implies. Each vertex still reaches the same vertices.
  • Critical path: Finds the longest chain of tasks that wait on each other, which sets how long the whole run takes however many tasks run in parallel.
  • Diff: Compares two graphs and returns the vertices, edges, weights and edge labels that differ, matching vertices by label.

All algorithms