I think I have understood a particular situation as described below, but I lack the theoretical knowledge to conduct a proof and I couldn\'t find any source that mentions it. If
Let adj[i][j]
be the adjacency entry from node i
to node j
and you've sorted it such that for all nodes i < j
, node i
is higher up the topological hierarchy than node j
.
Let's assume for a moment that your assumption was incorrect: that we have a counter-example for which adj[i][j] == 1
for i > j
(i.e., a one in the upper-right half of your matrix representation). This implies that there must be a cycle containing i
and j
, since our sorting guarantees that node j
is higher up than node i
yet we have adj[i][j] == 1
implies we can "climb" up the hierarchy. This is a contradiction, since we know we have a DAG. Therefore we have proven that your assumption is correct.
This is only correct if your adjacency matrix is constructed with the graph labels in sorted order. For a counterexample construct the adjacency matrix for B->C->A.
If you kept a hash of the true node to it's topological sort position and construct the adjacency matrix from that you could save some space on a large matrix, as you're saving O(n²) space in the matrix with an O(n) size hashtable.