Topological sort in OCaml

前端 未结 4 842
醉梦人生
醉梦人生 2020-12-28 16:21

I\'m trying to write topological sorting in ocaml, but I\'m a beginner (in OCaml & graphs algorithms) and I can\'t do this by myself.

It\'s easier for me to thin

4条回答
  •  不知归路
    2020-12-28 16:32

    [In case you don't know the term, where I write DAG below I mean "directed acyclic graph", or a collection of from/to edges connecting vertices such that there are no cycles.]

    One way to do it is to extend your partial order (your DAG structure) into a total order (so for every pair of distinct vertices u and v, either u is a successor of v or vice versa). Then you can sort your vertices into order: u comes before v if v is a successor of u.

    You can construct your total order by starting with the empty graph and adding one edge at a time from your original DAG. That is, an item (u, [v1; v2; ...; vn]) in your original DAG corresponds to the edges (u, v1), (u, v2), ..., (u, vn). For each such edge (u, v), find the predecessors P of u and the successors S of v from your total order. Then add (p, s) to your total order for all p in P U {u} and s in S U {v}.

    NOW! A faster way to do it is to find a root in your original DAG (i.e., a vertex with no predecessors) and do a depth first search from that root, ensuring you never visit the same vertex twice. Every time you backtrack in your traversal, you "output" the vertex you are leaving. This way you construct the topological sort of your DAG. If there are any vertices left over, lather rinse, and repeat until they're all done.

提交回复
热议问题