How to convert an undirected graph to a DAG?

前端 未结 4 1493
情深已故
情深已故 2021-02-08 07:40

The Wiki page says

Any undirected graph may be made into a DAG by choosing a total order for its vertices and orienting every edge from the earlier endpo

4条回答
  •  天涯浪人
    2021-02-08 08:32

    You can get a total order and turn the undirected graph into a DAG numbering nodes in reverse post order.

    Perform a post-order depth first traversal, assigning a number to each node as you leave it, in sequence from 1 to n. The order you visit adjacent nodes determines the direction of the edges in the DAG. Do not traverse edges, which lead from a higher numbered node to a lower numbered node - this breaks cycles, effectively determining that in the final DAG this edge will be in the opposite direction.

    This order gives a topological sort of the graph, it's a total order and since a topological ordering exists, the graph is turned into a DAG.

    EDIT: To clarify, once you've labelled nodes with their RPO-number, for each edge a <-> b in the original graph, the edge in the DAG is a -> b iff RPO-number(a) < RPO-number (b), otherwise the edge is b -> a.

    EDIT: The above it an overkill, though, it will work if some edges are directed and some not, if all are undirected, as pointed by @missingno, any order will suffice.

提交回复
热议问题