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.
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)
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)
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|).
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;
}
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).