Open In App

Add and Remove Edge in Adjacency List representation of a Graph

Last Updated : 05 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 
 

  • Adding an edge: Adding an edge is done by inserting both of the vertices connected by that edge in each others list. For example, if an edge between (u, v) has to be added, then u is stored in v’s vector list and v is stored in u’s vector list. (push_back)
  • Deleting an edge: To delete edge between (u, v), u’s adjacency list is traversed until v is found and it is removed from it. The same operation is performed for v.(erase)

Below is the implementation of the approach: 
 

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// A utility function to add an edge in an
// undirected graph.
void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
// A utility function to delete an edge in an
// undirected graph.
void delEdge(vector<int> adj[], int u, int v)
{
    // Traversing through the first vector list
    // and removing the second element from it
    for (int i = 0; i < adj[u].size(); i++) {
        if (adj[u][i] == v) {
            adj[u].erase(adj[u].begin() + i);
            break;
        }
    }
 
    // Traversing through the second vector list
    // and removing the first element from it
    for (int i = 0; i < adj[v].size(); i++) {
        if (adj[v][i] == u) {
            adj[v].erase(adj[v].begin() + i);
            break;
        }
    }
}
 
// A utility function to print the adjacency list
// representation of graph
void printGraph(vector<int> adj[], int V)
{
    for (int v = 0; v < V; ++v) {
        cout << "vertex " << v << " ";
        for (auto x : adj[v])
            cout << "-> " << x;
        printf("\n");
    }
    printf("\n");
}
 
// Driver code
int main()
{
    int V = 5;
    vector<int> adj[V];
 
    // Adding edge as shown in the example figure
    addEdge(adj, 0, 1);
    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
 
    // Deleting edge (1, 4)
    // as shown in the example figure
    delEdge(adj, 1, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
 
    return 0;
}


Java




// Java implementation of the above approach
import java.util.*;
 
class GFG
{
 
// A utility function to add an edge in an
// undirected graph.
static void addEdge(Vector<Integer> adj[],
                    int u, int v)
{
    adj[u].add(v);
    adj[v].add(u);
}
 
// A utility function to delete an edge in an
// undirected graph.
static void delEdge(Vector<Integer> adj[],
                    int u, int v)
{
    // Traversing through the first vector list
    // and removing the second element from it
    for (int i = 0; i < adj[u].size(); i++)
    {
        if (adj[u].get(i) == v)
        {
            adj[u].remove(i);
            break;
        }
    }
 
    // Traversing through the second vector list
    // and removing the first element from it
    for (int i = 0; i < adj[v].size(); i++)
    {
        if (adj[v].get(i) == u)
        {
            adj[v].remove(i);
            break;
        }
    }
}
 
// A utility function to print the adjacency list
// representation of graph
static void printGraph(Vector<Integer> adj[], int V)
{
    for (int v = 0; v < V; ++v)
    {
        System.out.print("vertex " + v+ " ");
        for (Integer x : adj[v])
            System.out.print("-> " + x);
        System.out.printf("\n");
    }
    System.out.printf("\n");
}
 
// Driver code
public static void main(String[] args)
{
    int V = 5;
    Vector<Integer> []adj = new Vector[V];
        for (int i = 0; i < V; i++)
            adj[i] = new Vector<Integer>();
     
    // Adding edge as shown in the example figure
    addEdge(adj, 0, 1);
    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
 
    // Deleting edge (1, 4)
    // as shown in the example figure
    delEdge(adj, 1, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the above approach
  
# A utility function to add an edge in an
# undirected graph.
def addEdge(adj, u, v):
 
    adj[u].append(v);
    adj[v].append(u);
     
# A utility function to delete an edge in an
# undirected graph.
def delEdge(adj,  u,  v):
     
    # Traversing through the first vector list
    # and removing the second element from it
    for i in range(len(adj[u])):
     
        if (adj[u][i] == v):
             
            adj[u].pop(i);
            break;
     
    # Traversing through the second vector list
    # and removing the first element from it
    for i in range(len(adj[v])):
     
        if (adj[v][i] == u):
             
            adj[v].pop(i);
            break;
      
# A utility function to pr the adjacency list
# representation of graph
def prGraph(adj,  V):
     
    for v in range(V):
         
        print("vertex " + str(v), end = ' ')
         
        for x in adj[v]:
            print("-> " + str(x), end = '')
             
        print()
    print()
     
# Driver code
if __name__=='__main__':
 
    V = 5;
    adj = [[] for i in range(V)]
  
    # Adding edge as shown in the example figure
    addEdge(adj, 0, 1);
    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
  
    # Print adjacency matrix
    prGraph(adj, V);
  
    # Deleting edge (1, 4)
    # as shown in the example figure
    delEdge(adj, 1, 4);
  
    # Print adjacency matrix
    prGraph(adj, V);
 
# This code is contributed by rutvik_56   


C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A utility function to add an edge in an
// undirected graph.
static void addEdge(List<int> []adj,
                    int u, int v)
{
    adj[u].Add(v);
    adj[v].Add(u);
}
 
// A utility function to delete an edge in an
// undirected graph.
static void delEdge(List<int> []adj,
                    int u, int v)
{
    // Traversing through the first vector list
    // and removing the second element from it
    for (int i = 0; i < adj[u].Count; i++)
    {
        if (adj[u][i] == v)
        {
            adj[u].RemoveAt(i);
            break;
        }
    }
 
    // Traversing through the second vector list
    // and removing the first element from it
    for (int i = 0; i < adj[v].Count; i++)
    {
        if (adj[v][i] == u)
        {
            adj[v].RemoveAt(i);
            break;
        }
    }
}
 
// A utility function to print the adjacency list
// representation of graph
static void printGraph(List<int> []adj, int V)
{
    for (int v = 0; v < V; ++v)
    {
        Console.Write("vertex " + v + " ");
        foreach (int x in adj[v])
            Console.Write("-> " + x);
        Console.Write("\n");
    }
    Console.Write("\n");
}
 
// Driver code
public static void Main(String[] args)
{
    int V = 5;
    List<int> []adj = new List<int>[V];
        for (int i = 0; i < V; i++)
            adj[i] = new List<int>();
     
    // Adding edge as shown in the example figure
    addEdge(adj, 0, 1);
    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
 
    // Deleting edge (1, 4)
    // as shown in the example figure
    delEdge(adj, 1, 4);
 
    // Printing adjacency matrix
    printGraph(adj, V);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




// JavaScript implementation of the approach
// to delete an edge in an undirected graph
 
const addEdge = (adj, u, v) => {
  // add the edge to the graph by adding v to the
  // list of u and adding u to the list of v
  adj[u].push(v);
  adj[v].push(u);
};
 
const delEdge = (adj, u, v) => {
  // find the index of v in the list of u and remove it
  const indexOfVInU = adj[u].indexOf(v);
  adj[u].splice(indexOfVInU, 1);
 
  // find the index of u in the list of v and remove it
  const indexOfUInV = adj[v].indexOf(u);
  adj[v].splice(indexOfUInV, 1);
};
 
const printGraph = (adj, V) => {
  for (let v = 0; v < V; v++) {
    console.log(`vertex ${v} `, adj[v].join("-> "));
  }
};
 
const main = () => {
  const V = 5;
  const adj = [];
  for (let i = 0; i < V; i++) {
    adj[i] = [];
  }
 
  // Adding edge as shown in the example figure
  addEdge(adj, 0, 1);
  addEdge(adj, 0, 4);
  addEdge(adj, 1, 2);
  addEdge(adj, 1, 3);
  addEdge(adj, 1, 4);
  addEdge(adj, 2, 3);
  addEdge(adj, 3, 4);
 
  // Printing adjacency matrix
  printGraph(adj, V);
 
  // Deleting edge (1, 4)
  // as shown in the example figure
  delEdge(adj, 1, 4);
 
  // Printing adjacency matrix
  printGraph(adj, V);
};
 
main();


Output: 

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.



Similar Reads

Add and Remove Edge in Adjacency Matrix representation of a Graph
Prerequisites: Graph and its representationsGiven an adjacency matrix g[][] of a graph consisting of N vertices, the task is to modify the matrix after insertion of all edges[] and removal of edge between vertices (X, Y). In an adjacency matrix, if an edge exists between vertices i and j of the graph, then g[i][j] = 1 and g[j][i] = 1. If no edge ex
13 min read
Comparison between Adjacency List and Adjacency Matrix representation of Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this article, we will understand the difference between the ways of representation of the graph. A graph can be represented in mainly two ways. They ar
4 min read
Convert Adjacency Matrix to Adjacency List representation of Graph
Prerequisite: Graph and its representations Given a adjacency matrix representation of a Graph. The task is to convert the given Adjacency Matrix to Adjacency List representation. Examples: Input: arr[][] = [ [0, 0, 1], [0, 0, 1], [1, 1, 0] ] Output: The adjacency list is: 0 -&gt; 2 1 -&gt; 2 2 -&gt; 0 -&gt; 1Input: arr[][] = [ [0, 1, 0, 0, 1], [1,
6 min read
Convert Adjacency List to Adjacency Matrix representation of a Graph
Given an adjacency list representation of a Graph, the task is to convert the given Adjacency List to Adjacency Matrix representation. Examples: Input: adjList[] = {{0 --&gt; 1 --&gt; 3}, {1 --&gt; 2}, {2 --&gt; 3}} Output: 0 1 0 10 0 1 00 0 0 10 0 0 0 Input: adjList[] = {{0 --&gt; 1 --&gt; 4}, {1 --&gt; 0 --&gt; 2 --&gt; 3 --&gt; 4}, {2 --&gt; 1 -
9 min read
Add and Remove vertex in Adjacency List representation of Graph
Prerequisites: Linked List, Graph Data Structure In this article, adding and removing a vertex is discussed in a given adjacency list representation. Let the Directed Graph be: The graph can be represented in the Adjacency List representation as: It is a Linked List representation where the head of the linked list is a vertex in the graph and all t
10 min read
Add and Remove vertex in Adjacency Matrix representation of Graph
A graph is a presentation of a set of entities where some pairs of entities are linked by a connection. Interconnected entities are represented by points referred to as vertices, and the connections between the vertices are termed as edges. Formally, a graph is a pair of sets (V, E), where V is a collection of vertices, and E is a collection of edg
15+ min read
Adjacency List Generation from Edge Connections
Given a list of undirected edge connections of size E, create an adjacency list for a graph with V nodes and E edges following 0-based indexing and return the adjacency list. Examples: Input: V = 4, E = 5, edges = [[0, 1], [1, 2], [2, 3], [0, 2], [1, 3]]Output: [[1, 2], [0, 2, 3], [1, 3, 0], [2, 1]]Explanation: Node 0 is connected to 1 2 Node numbe
6 min read
Level order traversal by converting N-ary Tree into adjacency list representation with K as root node
Given the root node of an N-ary tree and an integer K, the task is to convert the given tree into adjacency list representation and print the level order traversal considering vertex K as the root node. Example: Input: Tree in the image below, K = 5 Output:5 1 9 10 11 2 3 4 6 7 8 Input: Tree in the image below, K = 5 Output:5 12 3 4 7 8 Approach: T
9 min read
Prim’s MST for Adjacency List Representation | Greedy Algo-6
We recommend reading the following two posts as a prerequisite to this post. Greedy Algorithms | Set 5 (Prim’s Minimum Spanning Tree (MST)) Graph and its representationsWe have discussed Prim's algorithm and its implementation for adjacency matrix representation of graphs. The time complexity for the matrix representation is O(V^2). In this post, O
15+ min read
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
We recommend reading the following two posts as a prerequisite for this post. Greedy Algorithms | Set 7 (Dijkstra’s shortest path algorithm) Graph and its representations We have discussed Dijkstra's algorithm and its implementation for adjacency matrix representation of graphs. The time complexity for the matrix representation is O(V^2). In this p
15+ min read
Article Tags :
Practice Tags :