Solution: Remove an Edge
Learn how to delete an edge from a directed graph.
We'll cover the following...
Solution: Using graph traversal
class Program{/// <summary>/// A methos to remove an edge from the graph./// </summary>/// <param name="graph">A graph.</param>/// <param name="source">Source vertex.</param>/// <param name="destination">Destination vertex.</param>public static void RemoveEdge(Graph graph, int source, int destination){if (graph.V == 0){return;}if (source >= graph.V || source < 0){return;}if (destination >= graph.V || destination < 0){return;}AdjNode temp = graph.graph[source];// If head node itself holds the key to be deletedif (temp != null){if (temp.Vertex == destination){graph.graph[source] = temp.Next;return;}}AdjNode prev = null;while (temp != null){if (temp.Vertex == destination){break;}prev = temp;temp = temp.Next;}if (temp == null){return;}// Set the new link// from removed node's previous node to next nodeprev.Next = temp.Next;}// Main program to test above methodstatic void Main(string[] args){Graph g = new Graph(5);g.AddEdge(0, 1);g.AddEdge(0, 2);g.AddEdge(1, 3);g.AddEdge(1, 4);g.AddEdge(2, 4);Console.WriteLine("Before: ");g.PrintGraph();RemoveEdge(g, 1, 3);Console.WriteLine("After: ");g.PrintGraph();}}
Explanation
This ...