...

/

Solution: Transpose a Graph

Solution: Transpose a Graph

Learn how to find the transpose of a graph.

Solution: Traversal of an adjacency list

class Program
{
/// <summary>
/// Transposes the given graph.
/// </summary>
/// <param name="graph">The graph.</param>
/// <returns>A new transposed graph of the given graph.</returns>
public static Graph Transpose(Graph myGraph)
{
int V = myGraph.V;
Graph newGraph = new Graph(V);
for (int source = 0; source < V; source++)
{
AdjNode temp = myGraph.graph[source];
while (temp != null)
{
int destination = temp.Vertex;
// Now the source is destination and vice versa
newGraph.AddEdge(destination, source);
temp = temp.Next;
}
}
return newGraph;
}
// Main program to test the above function
static void Main(string[] args)
{
int V = 5;
Graph g = new Graph(V);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(1, 3);
g.AddEdge(1, 4);
Graph newG = Transpose(g);
// Printing the transposed graph
for (int i = 0; i < newG.V; i++)
{
Console.Write($"Adjacency list of vertex {i}\n head");
AdjNode temp = newG.graph[i];
while (temp != null)
{
Console.Write($" -> {temp.Vertex}");
temp = temp.Next;
}
Console.WriteLine(" \n");
}
}
}

Explanation

This solution is pretty straightforward. We just make another graph but start reversing it. We traverse the ...