How to reverse a graph in linear time?

前端 未结 4 1846
天涯浪人
天涯浪人 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:00
    G = {"A":["B", "C","D"],"B":["C", "E"], "C":["D", "E"],"D":[],"E":["D"] }
    res ={}
    for k in G.keys():
        for val in G[k]:
            if val not in res.keys():
                res[val] = [k]
            else:
                res[val].append(k)
    
    print(res)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-02-08 07:08

    Reversing the adjacency lists of a Directed Graph can be done in linear time. We traverse the graph only once. Order of complexity will be O(|V|+|E|).

    1. Maintain a HashMap of Adjaceny Lists where the key is the vertex label and the value is an ArrayList of adjacent vertices of the key vertex.
    2. For reversing, create a new HashMap of the same kind. Scan the original hash map and for each key you come across, traverse the corresponding list.
    3. For each vertex found in the value list, add a key in the new hashMap, putting the key of the original HashMap as an entry in the ArrayList corresponding to the new key in the new HashMap.
    public static HashMap<Character,ArrayList <Character>> getReversedAdjLists(RGraph g)
    {
        HashMap <Character, ArrayList<Character>> revAdjListMap = new HashMap <Character, ArrayList<Character>>();
        Set <Character> oldLabelSet = g.adjListMap.keySet();
    
        for(char oldLabel:oldLabelSet)
        {
            ArrayList<Character> oldLabelList = g.adjListMap.get(oldLabel);
    
            for (char newLabel : oldLabelList)
            {
                ArrayList<Character> newLabelList = revAdjListMap.get(newLabel);
    
                if (newLabelList == null)
                {
                    newLabelList = new ArrayList<Character>();
                    newLabelList.add(oldLabel);
                }
                else if ( ! newLabelList.contains(oldLabel))
                {
                    newLabelList.add(oldLabel);
                }
    
                revAdjListMap.put(newLabel, newLabelList);
            }
        }
    
        return revAdjListMap;
    }
    
    0 讨论(0)
  • 2021-02-08 07:10

    I think reversing the graph by traversing the list takes O(V2), since for each vertex you must add or delete (V-1) edges.

    As for Dijkstra's algorithm, as I understand it, if you represent the graph as a matrix or list the algorithm takes O(V2), but some other data structures are faster. The fastest known is a Fibonacci heap, which gives O(E + VlogV).

    0 讨论(0)
提交回复
热议问题