Topological sort accepts graph with cycles
erikmaarten opened this issue · comments
A topological sorting is only possible for a DAG, but this function seems to accept any graph. Is this intentional (perhaps for performance reasons)? If not, perhaps topologicalSort
could return a Result
with an error for graphs that don't have a topological ordering.
You're right, I'm definitely not comfortable with that (e.g. topologicalSort
not returning a Result
). But there's stronglyConnectedComponents
, which will return all strongly connected components in a topological order. You could detect cycles by simple checking if the resulting list has length equal to the size of the graph and if so, get a valid topoligical ordering by extracting each singleton graph.
Thanks, that's neat. I'd be happy to make a PR changing topologicalSort
to use this strategy and return a Result
. It will be a little slower, but checking for cycles will necessarily be slower than not doing it anyway so it seems like a decent and simple solution.
That'd be great! I imagine an Result
-like type either returning the ordering or the result of stronglyConnectedComponents
(one could even call the other), but whatever you think might be best.