...

/

Solution: Remove an Edge

Solution: Remove an Edge

In this review lesson, we will give a detailed analysis of the solution to remove an edge from a directed graph.

Solution: using graph traversal

def remove_edge(graph, source, destination):
"""
A function to remove an edge
:param graph: A graph
:param source: Source Vertex
:param destination: Destination Vertex
"""
if graph.V == 0:
return graph
if source >= graph.V or source < 0:
return graph
if destination >= graph.V or destination < 0:
return graph
temp = graph.graph[source]
# If head node itself holds the key to be deleted
if temp is not None:
if temp.vertex == destination:
graph.graph[source] = temp.next
temp = None
return
while temp is not None:
if destination == temp.vertex:
break
prev = temp
temp = temp.next
if temp is None:
return
# Set the new link
# from removed node's previous node to next node
prev.next = temp.next
temp = None
# Main program to test above function
if __name__ == "__main__":
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 4)
print("Before: ")
g.print_graph()
remove_edge(g, 1, 3)
print("After: ")
g.print_graph()

Explanation

This challenge is very similar to the deletion in the linked list.

Our vertices are stored in a linked list. First, we access the source linked list. If the head node of the source linked list holds the key to be deleted, we shift the head one step forward ...