Added the program of Graph Reversal #1840
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Reverse a Directed Graph
Problem Statement:
Suppose we have a directed graph, we have to find its reverse so if an edge goes from i to j, it now goes from j to i. Here input will be an adjacency list, and if there are n nodes, the nodes will be (0, 1, ..., n-1).
Approach:
The approach to transposing a directed graph involves creating a new structure to hold reversed edges. For each vertex, the algorithm iterates through its outgoing edges and appends the vertex to the list of the target vertex in the new structure. This efficiently constructs the transposed graph in linear time relative to the number of vertices and edges.
Algorithm Steps:
Define Structures:
AdjList
structure, a dynamic array to hold adjacent nodes for each node.Graph
structure containing an array ofAdjList
s to represent the adjacency lists for all nodes.Initialize the Graph:
initGraph
that initializes aGraph
with a given number of nodes.AdjList
with a small initial capacity.Add an Edge:
pushBack
for adding an edge to a node'sAdjList
.AdjList
is full, double the capacity and reallocate memory.Transpose the Graph:
solve
to transpose the graph:Graph
(the transposed graph) with the same number of nodes as the original.Print the Graph:
printGraph
to display the adjacency lists of the graph:Example Usage:
solve
function to transpose the graph.Time Complexity:
O(V + E)
, whereV
is the number of vertices andE
is the number of edges, as it processes each vertex and edge once.Sample Input:
Sample Output:
Explanation of Sample:
The input
graph = [[1,2],[4],[4],[1,2],[3]]
represents a directed graph as an adjacency list where:The reversed graph representation is
ans = [[], [0, 3], [0, 3], [4], [1, 2]]
, which means:Diagrammatic Representation of the input:
Diagrammatic Representation of the output: