...

/

Solution: Transpose a Graph

Solution: Transpose a Graph

In this review lesson, we will give a detailed analysis of how to find the transpose of a graph.

Solution: traversal of an adjacency list

def transpose(my_graph):
"""
Transpose the given graph
:param graph: The graph
:return: a new transposed graph of the given graph
"""
new_graph = Graph(my_graph.V) # Creating a new graph
for source in range(my_graph.V):
while my_graph.graph[source] is not None:
destination = my_graph.graph[source].vertex
# Now the source is destination and vice versa
new_graph.add_edge(destination, source)
my_graph.graph[source] = my_graph.graph[source].next
return new_graph
# Main program to test the above function
if __name__ == "__main__":
V = 5
g = Graph(V)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
new_g = transpose(g)
new_g.print_graph()

Explanation

This solution is pretty straight forward. Just make another graph, but start reversing it. Traverse the adjacency list of the given graph and—on encountering a vertex vv in the adjacency list of vertex uu ...