![]() |
VOOZH | about |
Prerequisites: Graph and Its Representation
In this article, adding and removing edge is discussed in a given adjacency list representation.
A vector has been used to implement the graph using adjacency list representation. It is used to store the adjacency lists of all the vertices. The vertex number is used as the index in this vector.
Example:
Below is a graph and its adjacency list representation:
If the edge between 1 and 4 has to be removed, then the above graph and the adjacency list transforms to:
Approach: The idea is to represent the graph as an array of vectors such that every vector represents adjacency list of the vertex.
Below is the implementation of the approach:
vertex 0 -> 1-> 4 vertex 1 -> 0-> 2-> 3-> 4 vertex 2 -> 1-> 3 vertex 3 -> 1-> 2-> 4 vertex 4 -> 0-> 1-> 3 vertex 0 -> 1-> 4 vertex 1 -> 0-> 2-> 3 vertex 2 -> 1-> 3 vertex 3 -> 1-> 2-> 4 vertex 4 -> 0-> 3
Time Complexity: Removing an edge from adjacent list requires, on the average time complexity will be O(|E| / |V|) , which may result in cubical complexity for dense graphs to remove all edges.
Auxiliary Space: O(V) , here V is number of vertices.