Seeking algorithm to invert (reverse? mirror? turn inside-out) a DAG

后端 未结 5 1441
我寻月下人不归
我寻月下人不归 2021-02-01 09:54

I\'m looking for an algorithm to \"invert\" (reverse? turn inside-out?) a DAG:

       A*      # I can\'t ascii-art the arrows, so just
      / \\      # pretend          


        
5条回答
  •  醉话见心
    2021-02-01 10:34

    I solved this with a simple graph traversal. Keep in mind topological sorting will only be useful for directed acyclic graphs.

    I used an adjacency list, but you can do a similar thing with an adjacency matrix.

    In Python it looks like this:

    # Basic Graph Structure
    g = {}
    g[vertex] = [v1, v2, v3] # Each vertex contains a lists of its edges
    

    To find all the edges for v, you then traverse the list g[v] and that will give you all (v, u) edges.

    To build the reversed graph make a new dictionary and build it something like this:

        reversed = {}
        for v in g:
            for e in g[v]:
                if e not in reversed:
                    reversed[e] = []
                reversed[e].append(v)
    

    This is very memory intensive for large graphs (doubling your memory usage), but it is a very easy way to work with them and quite quick. There may be more clever solutions out there involving building a generator and using a dfs algorithm of some sort, but I have not put a lot of thought into it.

提交回复
热议问题