0

I am looking for an algorithm which can take a graph and topologically sort it such that it produces a set of lists, each which contains the topologically sorted vertices of a disjoint subgraph.

The difficult part is merging the lists when a node depends on a node in two different lists.

Here is my incomplete code/pseudocode where graph is a dict {node: [node, node, ...]}

Topologically sort graph into disjoint lists

sorted_subgraphs = []

while graph:
    cyclic = True
    for node, edges in list(graph.items()):
        for edge in edges:
            if edge in graph:
                break
        else:
            del graph[node]
            cyclic = False

            sub_sorted = []
            for edge in edges:
                bucket.extend(...) # Get the list with edge in it, and remove it from sorted_subgraphs
            bucket.append(node)

            sorted_subgraphs.append(bucket)

    if cyclic:
        raise Exception('Cyclic graph')
shane
  • 1,742
  • 2
  • 19
  • 36

1 Answers1

0

First divide it into disjoint subgraphs using a flood fill algorithm, and then topologically sort each one.

btilly
  • 43,296
  • 3
  • 59
  • 88
  • How can the flood fill algorithm identify an entire subgraph of a directed graph. Depending on which node you begin with, the algorithm may not get to nodes further upstream, and absolutely will not if the graph is acyclic. – shane Feb 02 '17 at 23:19
  • @shane Construct an undirected graph out of the directed graph, do a flood fill on that, now that it is partitioned, you can go back to the original graph and topologically sort each disjoint subgraph. – btilly Feb 03 '17 at 02:30