All Ancestors of a Node in a Directed Acyclic Graph
For every node of a graph whose one-way links never form a circle, list all the nodes that can reach it.
A graph has nn - 1edges[a, b]edgesab
Example 1
Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
Explanation: 6 can be reached from 3 and 4, and through them from 0, 1 and 2.
Example 2
Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]
Explanation: every node has a link to every bigger node, so each node's ancestors are all the smaller nodes.
The Idea
Picture streams running downhill. Water flows from one point to the next, never back up, so it can never go round in a circle. The ancestors of a point are all the points upstream of it: the places whose water passes through it sooner or later.
The problem uses the usual words for this. The points are nodes and the one-way links are edges. A graph whose edges go one way only is called directed, and one where you can never return to a node you passed is called acyclic, meaning without cycles. Together that is a directed acyclic graph, or DAG for short.
Take node 6 in Example 1. Two edges lead into it, from 3 and from 4. Edges lead into 3 from 0 and 1, and into 4 from 0 and 2. So the nodes upstream of 6 are 0, 1, 2, 3 and 4, which is the list [0,1,2,3,4]
That walk went backwards, against the edges, and it met the ancestors in the order 3, 4, 0, 1, 0, 2. Node 0 showed up twice, and the list still had to be sorted. Is there a way to collect the ancestors that avoids both?
Turn the question around. Instead of asking which nodes are upstream of 6, ask where the water from node 0 goes. Look at the picture below.
Starting at 0, the orange edges lead to 3 and 4, and from there to 5, 6 and 7. Every node coloured orange can be reached from 0, so each of them gets 0 in its ancestor list. Node 6 is reached twice, once through 3 and once through 4, so the search has to remember the nodes it has already seen.
Now do the same from node 1, then from node 2, and so on up to the last node. Each start node is added to the lists of the nodes it reaches, and the start nodes come in increasing order. So every list fills up in increasing order too, and no sort is needed at the end.
Solution Approach
Turning that idea into code means settling four things: how to store the edges, how to walk from one start node, how to avoid adding an ancestor twice, and why the lists need no sort.
Storing the edges
Where does a search look up the nodes an edge leads to? The input is just a list of pairs, so first it is turned into one list per node, holding the nodes that node's edges point to. These are the node's children. For Example 1 the lists are:
- 0: [3, 4], 1: [3], 2: [4, 7]
- 3: [5, 6, 7], 4: [6]
- 5, 6 and 7: empty
Keeping one list of neighbours per node like this is called an adjacency list. Each pair goes into the list of its first node only, because the search only walks edges forwards.
Walking from one start node
How does a search from 0 reach everything downstream? It follows one path as deep as it goes, then backs up to the last node that still has an unexplored child. In the picture, a search could go 0, 3, 5, back up to 3 for 6 and 7, then over to 4. Searching in this way is called depth-first search, or DFS. Which child is tried first does not change which nodes get reached.
The nodes still waiting to be explored go on a stack, a pile where the node put on last is taken off first. Java's ArrayDequepushpopArrayDeque
Not adding an ancestor twice
What stops node 6 from getting 0 twice? Each search keeps a booleanvisited
Why the lists come out sorted
The searches run from start node 0, then 1, then 2, and each adds only its own start node to the lists. So a list receives 0 before 1, 1 before 2, and so on. This does not depend on which way the edges point, only on the order of the start nodes. The backward walk from the Idea finds the same ancestors, but would need a sort for every list.
Java Solution
The method getAncestors
- First, create two lists of lists,
andchildren , with one empty list per node.ancestors becomes the answer. Then, for every edgeancestors , adde to the children ofe[1] .e[0] - Run one search per start node with a loop, moving
from 0 up tosrc . For eachn - 1 , create a freshsrc array and avisited holding onlystack , and marksrc as visited.src - While the stack is not empty, pop a node
and look at each of its childrenu . Ifv is not visited yet, mark it, addv to the ancestors ofsrc , and pushv so its own children get explored.v - When the last search is done, return
.ancestors
The main
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class AllAncestorsOfNodeInDAG {
public static List<List<Integer>> getAncestors(int n, int[][] edges) {
List<List<Integer>> children = new ArrayList<>();
List<List<Integer>> ancestors = new ArrayList<>();
for (int i = 0; i < n; i++) {
children.add(new ArrayList<>());
ancestors.add(new ArrayList<>());
}
for (int[] e : edges) {
children.get(e[0]).add(e[1]); // edge from e[0] to e[1]
}
for (int src = 0; src < n; src++) { // start nodes in increasing order
boolean[] visited = new boolean[n]; // fresh for every search
Deque<Integer> stack = new ArrayDeque<>();
stack.push(src);
visited[src] = true;
while (!stack.isEmpty()) {
int u = stack.pop();
for (int v : children.get(u)) {
if (!visited[v]) {
visited[v] = true;
ancestors.get(v).add(src); // src can reach v
stack.push(v);
}
}
}
}
return ancestors;
}
public static void main(String[] args) {
System.out.println(getAncestors(8, new int[][] {{0, 3}, {0, 4}, {1, 3}, {2, 4}, {2, 7},
{3, 5}, {3, 6}, {3, 7}, {4, 6}}));
System.out.println(getAncestors(5, new int[][] {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 2},
{1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}));
System.out.println(getAncestors(4, new int[][] {{0, 1}, {0, 2}, {1, 3}, {2, 3}}));
System.out.println(getAncestors(3, new int[][] {}));
System.out.println(getAncestors(4, new int[][] {{3, 2}, {2, 1}, {1, 0}}));
}
}
Running it prints:
[[], [], [], [0, 1], [0, 2], [0, 1, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3]]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
[[], [0], [0], [0, 1, 2]]
[[], [], []]
[[1, 2, 3], [2, 3], [3], []]
The first line is Example 1, with [0, 1, 2, 3, 4][0, 1, 2]
Look at the last line, [[1, 2, 3], [2, 3], [3], []]
Does the visited[0, 0, 1, 2, 3, 4]
Complexity
The work is n
- Time: O(n × (n + m)), with m the number of edges, because each of the n searches sets up a
array of n entries and follows each edge at most once.visited - Space: O(n2), because when every node reaches every bigger node, as in Example 2, the output holds n(n - 1)/2 ancestors, and the other structures add only O(n + m).
The search used here is explained on its own in