Why DFS Topological Sort Writes Nodes on Backtracking
dev.to·15h·
Discuss: DEV
Flag this post

Let us have two components, A and B. We traverse A first and then move on to B such that, while visiting B, we find an edge B → A (remember that we have already traversed A).

So whatever component we traverse after A must appear before A in the final output — like B, A — so that if we get an edge B → A, it satisfies the rules of topological sorting.

But in an array, we can only insert efficiently at the end (inserting at the front is costly). So we just keep inserting at the end, getting something like A, B, but knowing we’ll reverse it later to become B, A.

However, that final reversal would also flip the internal order of each component (A and B). To preserve that, we write each component already reversed — that is, we record nodes while backtracking.

So when the global …

Similar Posts

Loading similar posts...