How to reverse a graph in linear time?

前端 未结 4 1842
天涯浪人
天涯浪人 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: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> getReversedAdjLists(RGraph g)
    {
        HashMap > revAdjListMap = new HashMap >();
        Set  oldLabelSet = g.adjListMap.keySet();
    
        for(char oldLabel:oldLabelSet)
        {
            ArrayList oldLabelList = g.adjListMap.get(oldLabel);
    
            for (char newLabel : oldLabelList)
            {
                ArrayList newLabelList = revAdjListMap.get(newLabel);
    
                if (newLabelList == null)
                {
                    newLabelList = new ArrayList();
                    newLabelList.add(oldLabel);
                }
                else if ( ! newLabelList.contains(oldLabel))
                {
                    newLabelList.add(oldLabel);
                }
    
                revAdjListMap.put(newLabel, newLabelList);
            }
        }
    
        return revAdjListMap;
    }
    

提交回复
热议问题