How to reverse a graph in linear time?

前端 未结 4 1845
天涯浪人
天涯浪人 2021-02-08 06:46

I know there are two ways to represent my graph: one is using a matrix, and the other one is using a list.

If I use a matrix, I have to flip all the bits in the matrix.

4条回答
  •  长发绾君心
    2021-02-08 07:01

    Since I see a couple of comments asking about an in place graph transpose (reversal), here is my version of it. Please note this will only work on DAGs.Feedback and suggestions for improvement would be welcome

    def transpose(G):
        """
        Return the transpose of a directed graph i.e. all the edges are reversed (In Place)
        """
        #note this is not a standard lib function afaik and you would have to 
        #implement topological sort but that should be easy
        topsort = topological_sort(G) 
        topsort.reverse() # we want to process starting from sink node
        for v in topsort:
            for node in G[v]:
                G[node].append(v)
            #  remove all older members of the vertex 'v'  
            G[v] = []
        print(G)
    

提交回复
热议问题