Solution: Transpose a Graph
In this review lesson, we will give a detailed analysis of how to find the transpose of a graph.
We'll cover the following...
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 graphfor 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 versanew_graph.add_edge(destination, source)my_graph.graph[source] = my_graph.graph[source].nextreturn new_graph# Main program to test the above functionif __name__ == "__main__":V = 5g = 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 in the adjacency list of vertex ...