A directed graph consists of vertices and directed edges that connect these vertices. The task is to write an algorithm that computes the reversal of a directed graph. For any directed edge A -> B, you must reverse its direction to B -> A. The output graph should have all the edges reversed.
Input:
Graph:
A -> B
B -> C
C -> D
Output:
Reversed Graph: A <- B
B <- C
C <- D
Explanation:
The original graph has edges:- A → B → C → D
Reversing these edges gives:- B ← A, C ← B, and D ← C.
Input:
Graph:
P -> Q
Q -> R
R -> S
S -> P
Output:
Reversed Graph: P <- Q
Q <- R
R <- S
S <- P
Explanation:
The original graph forms a cycle:- P → Q → R → S → P.Reversing these edges gives:- Q ← P, R ← Q, S ← R, and P ← S.
Graphs as adjacency lists: To efficiently represent the graph, we’ll use adjacency lists. For each vertex, we will maintain a list of vertices it references.
Edge reversal: To reverse the graph, we examine all edges. If vertex u points to vertex v, then we reverse the edge to make v point to u. This involves reconstructing the adjacency list.
python classSolution:
defreverseGraph(self, graph):
# Initialize a new graph for the reversed edges reversed_graph = {node: [] for node in graph}
# Traverse the original graph and reverse edgesfor node in graph:
for neighbour in graph[node]:
if neighbour notin reversed_graph:
reversed_graph[neighbour] = []
reversed_graph[neighbour].append(node)
return reversed_graph
# Example usageif __name__ =="__main__":
solution = Solution()
graph = {
'A': ['B'],
'B': ['C'],
'C': ['D']
}
reversed_graph = solution.reverseGraph(graph)
print(reversed_graph)