Open In App

Add and Remove Edge in Adjacency Matrix representation of a Graph

Last Updated : 30 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites: Graph and its representations
Given 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 exists between these two vertices, then g[i][j] = 0 and g[j][i] = 0.

Examples:

Input: N = 6, Edges[] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 3}, {2, 3}, {2, 4}, {2, 5}, {3, 5}}, X = 2, Y = 3 
Output: 
Adjacency matrix after edge insertion:
0 1 1 1 1 0 
1 0 0 1 0 0 
1 0 0 1 1 1 
1 1 1 0 0 1 
1 0 1 0 0 0 
0 0 1 1 0 0
Adjacency matrix after edge removal:
0 1 1 1 1 0 
1 0 0 1 0 0 
1 0 0 0 1 1 
1 1 0 0 0 1 
1 0 1 0 0 0 
0 0 1 1 0 0 
Explanation: 
The graph and the corresponding adjacency matrix after insertion of edges:

The graph after removal and adjacency matrix after removal of edge between vertex X and Y:

Input: N = 6, Edges[] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 3}, {2, 3}, {2, 4}, {2, 5}, {3, 5}}, X = 3, Y = 5 
Output: 
Adjacency matrix after edge insertion:
0 1 1 1 1 0 
1 0 0 1 0 0 
1 0 0 1 1 1 
1 1 1 0 0 1 
1 0 1 0 0 0 
0 0 1 1 0 0
Adjacency matrix after edge removal:
0 1 1 1 1 0 
1 0 0 1 0 0 
1 0 0 1 1 1 
1 1 1 0 0 0 
1 0 1 0 0 0 
0 0 1 0 0 0

Approach: 
Initialize a matrix of dimensions N x N and follow the steps below:

  • Inserting an edge: To insert an edge between two vertices suppose i and j, set the corresponding values in the adjacency matrix equal to 1, i.e. g[i][j]=1 and g[j][i]=1 if both the vertices i and j exists.
  • Removing an edge: To remove an edge between two vertices suppose i and j, set the corresponding values in the adjacency matrix equal to 0. That is, set g[i][j]=0 and g[j][i]=0 if both the vertices i and j exists.

Below is the implementation of the above approach:

C++




// C++ program to add and remove edge
// in the adjacency matrix of a graph
 
#include <iostream>
using namespace std;
 
class Graph {
private:
    // Number of vertices
    int n;
 
    // Adjacency matrix
    int g[10][10];
 
public:
    // Constructor
    Graph(int x)
    {
        n = x;
 
        // Initializing each element of the
        // adjacency matrix to zero
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                g[i][j] = 0;
            }
        }
    }
 
    // Function to display adjacency matrix
    void displayAdjacencyMatrix()
    {
        // Displaying the 2D matrix
        for (int i = 0; i < n; i++) {
            cout << "\n";
            for (int j = 0; j < n; j++) {
                cout << " " << g[i][j];
            }
        }
    }
 
    // Function to update adjacency
    // matrix for edge insertion
    void addEdge(int x, int y)
    {
        // Checks if the vertices
        // exist in the graph
        if ((x < 0) || (x >= n)) {
            cout << "Vertex" << x
                 << " does not exist!";
        }
        if ((y < 0) || (y >= n)) {
            cout << "Vertex" << y
                 << " does not exist!";
        }
 
        // Checks if it is a self edge
        if (x == y) {
            cout << "Same Vertex!";
        }
 
        else {
            // Insert edge
            g[y][x] = 1;
            g[x][y] = 1;
        }
    }
 
    // Function to update adjacency
    // matrix for edge removal
    void removeEdge(int x, int y)
    {
        // Checks if the vertices
        // exist in the graph
        if ((x < 0) || (x >= n)) {
            cout << "Vertex" << x
                 << " does not exist!";
        }
        if ((y < 0) || (y >= n)) {
            cout << "Vertex" << y
                 << " does not exist!";
        }
 
        // Checks if it is a self edge
        if (x == y) {
            cout << "Same Vertex!";
        }
 
        else {
            // Remove edge
            g[y][x] = 0;
            g[x][y] = 0;
        }
    }
};
 
// Driver Code
int main()
{
    int N = 6, X = 2, Y = 3;
 
    Graph obj(N);
 
    // Adding edges to the graph
    obj.addEdge(0, 1);
    obj.addEdge(0, 2);
    obj.addEdge(0, 3);
    obj.addEdge(0, 4);
    obj.addEdge(1, 3);
    obj.addEdge(2, 3);
    obj.addEdge(2, 4);
    obj.addEdge(2, 5);
    obj.addEdge(3, 5);
 
    cout << "Adjacency matrix after"
         << " edge insertions:\n";
    obj.displayAdjacencyMatrix();
 
    obj.removeEdge(X, Y);
 
    cout << "\nAdjacency matrix after"
         << " edge removal:\n";
    obj.displayAdjacencyMatrix();
 
    return 0;
}


Java




// Java program to add and remove edge
// in the adjacency matrix of a graph
 
class Graph {
 
    // Number of vertices
    private int n;
 
    // Adjacency matrix
    private int[][] g = new int[10][10];
 
    // Constructor
    Graph(int x)
    {
        this.n = x;
 
        // Initializing each element of the
        // adjacency matrix to zero
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                g[i][j] = 0;
            }
        }
    }
 
    // Function to display adjacency matrix
    public void displayAdjacencyMatrix()
    {
        // Displaying the 2D matrix
        for (int i = 0; i < n; ++i) {
            System.out.println();
            for (int j = 0; j < n; ++j) {
                System.out.print(" " + g[i][j]);
            }
        }
 
        System.out.println();
    }
 
    // Function to update adjacency
    // matrix for edge insertion
    public void addEdge(int x, int y)
    {
        // Checks if the vertices exists
        if ((x < 0) || (x >= n)) {
            System.out.printf("Vertex " + x
                              + " does not exist!");
        }
        if ((y < 0) || (y >= n)) {
            System.out.printf("Vertex " + y
                              + " does not exist!");
        }
 
        // Checks if it is a self edge
        if (x == y) {
            System.out.println("Same Vertex!");
        }
 
        else {
            // Insert edge
            g[y][x] = 1;
            g[x][y] = 1;
        }
    }
 
    // Function to update adjacency
    // matrix for edge removal
    public void removeEdge(int x, int y)
    {
        // Checks if the vertices exists
        if ((x < 0) || (x >= n)) {
            System.out.printf("Vertex " + x
                              + " does not exist!");
        }
        if ((y < 0) || (y >= n)) {
            System.out.printf("Vertex " + y
                              + " does not exist!");
        }
 
        // Checks if it is a self edge
        if (x == y) {
            System.out.println("Same Vertex!");
        }
 
        else {
            // Remove edge
            g[y][x] = 0;
            g[x][y] = 0;
        }
    }
}
 
// Driver Code
class Main {
    public static void main(String[] args)
    {
 
        int N = 6, X = 2, Y = 3;
        Graph obj = new Graph(N);
 
        // Inserting edges
        obj.addEdge(0, 1);
        obj.addEdge(0, 2);
        obj.addEdge(0, 3);
        obj.addEdge(0, 4);
        obj.addEdge(1, 3);
        obj.addEdge(2, 3);
        obj.addEdge(2, 4);
        obj.addEdge(2, 5);
        obj.addEdge(3, 5);
 
        System.out.println("Adjacency matrix after"
                           + " edge insertions:");
        obj.displayAdjacencyMatrix();
 
        obj.removeEdge(2, 3);
 
        System.out.println("\nAdjacency matrix after"
                           + " edge removal:");
        obj.displayAdjacencyMatrix();
    }
}


Python3




# Python3 program to add and remove edge
# in adjacency matrix representation of a graph
     
class Graph:
     
    # Number of vertices
    __n = 0
     
    # Adjacency matrix
    __g = [[0 for x in range(10)]
              for y in range(10)]
         
    # Constructor
    def __init__(self, x):
        self.__n = x
     
        # Initializing each element of
        # the adjacency matrix to zero
        for i in range(0, self.__n):
            for j in range(0, self.__n):
                self.__g[i][j] = 0
                 
    # Function to display adjacency matrix            
    def displayAdjacencyMatrix(self):
         
        # Displaying the 2D matrix
        for i in range(0, self.__n):
            print()
            for j in range(0, self.__n):
                print("", self.__g[i][j], end = "")
     
    # Function to update adjacency
    # matrix for edge insertion            
    def addEdge(self, x, y):
         
        # Checks if the vertices
        # exist in the graph
        if (x < 0) or (x >= self.__n):
            print("Vertex {} does not exist!".format(x))
        if (y < 0) or (y >= self.__n):
            print("Vertex {} does not exist!".format(y))
             
        # Checks if it is a self edge
        if(x == y):
            print("Same Vertex!")
 
        else:
             
            # Adding edge between the vertices
            self.__g[y][x] = 1
            self.__g[x][y] = 1
     
    # Function to update adjacency
    # matrix for edge removal        
    def removeEdge(self, x, y):
         
        # Checks if the vertices
        # exist in the graph
        if (x < 0) or (x >= self.__n):
            print("Vertex {} does not exist!".format(x))
        if (y < 0) or (y >= self.__n):
            print("Vertex {} does not exist!".format(y))
             
        # Checks if it is a self edge
        if(x == y):
            print("Same Vertex!")
 
        else:
             
            # Remove edge from between
            # the vertices
            self.__g[y][x] = 0
            self.__g[x][y] = 0
 
# Driver code   
 
# Creating an object of class Graph
obj = Graph(6);
         
# Adding edges to the graph
obj.addEdge(0, 1)
obj.addEdge(0, 2)
obj.addEdge(0, 3)
obj.addEdge(0, 4)
obj.addEdge(1, 3)
obj.addEdge(2, 3)
obj.addEdge(2, 4)
obj.addEdge(2, 5)
obj.addEdge(3, 5)
     
# Edges added to the adjacency matrix
print("Adjacency matrix after "
      "edge insertions:\n")
obj.displayAdjacencyMatrix();
         
# Removing the edge between vertices
# "2" and "3" from the graph
obj.removeEdge(2, 3);
     
# The adjacency matrix after
# removing the edge
print("\nAdjacency matrix after "
      "edge removal:\n")
obj.displayAdjacencyMatrix();
 
# This code is contributed by amarjeet_singh


C#




// C# program to add and remove edge
// in adjacency matrix representation
// of a graph
using System;
     
class Graph{
     
// Number of vertices
private int n;
 
// Adjacency matrix
private int[,] g = new int[10, 10];
 
// Constructor
public Graph(int x)
{
    this.n = x;
 
    // Initializing each element of
    // the adjacency matrix to zero
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            g[i, j] = 0;
        }
    }
}
 
// Function to display adjacency matrix
public void displayAdjacencyMatrix()
{
     
    // Displaying the 2D matrix
    for(int i = 0; i < n; ++i)
    {
        Console.WriteLine();
        for(int j = 0; j < n; ++j)
        {
            Console.Write(" " + g[i, j]);
        }
    }
}
 
// Function to update adjacency
// matrix for edge insertion
public void addEdge(int x, int y)
{
     
    // Checks if the vertices exist
    // in the graph
    if ((x < 0) || (x >= n))
    {
        Console.WriteLine("Vertex {0} does " +
                          "not exist!", x);
    }
    if ((y < 0) || (y >= n))
    {
        Console.WriteLine("Vertex {0} does " +
                          "not exist!", y);
    }
 
    // Checks if it is a self edge
    if (x == y)
    {
        Console.WriteLine("Same Vertex!");
    }
     
    else
    {
         
        // Adding edge between the vertices
        g[y, x] = 1;
        g[x, y] = 1;
    }
}
 
// Function to update adjacency
// matrix for edge removal
public void removeEdge(int x, int y)
{
     
    // Checks if the vertices exist
    // in the graph
    if ((x < 0) || (x >= n))
    {
        Console.WriteLine("Vertex {0} does" +
                          "not exist!", x);
    }
    if ((y < 0) || (y >= n))
    {
        Console.WriteLine("Vertex {0} does" +
                          "not exist!", y);
    }
 
    // Checks if it is a self edge
    if (x == y)
    {
        Console.WriteLine("Same Vertex!");
    }
     
    else
    {
         
        // Remove edge from between
        // the vertices
        g[y, x] = 0;
        g[x, y] = 0;
    }
}
}
     
class GFG{
     
// Driver code
public static void Main(String[] args)
{
     
    // Creating an object of class Graph
    Graph obj = new Graph(6);
 
    // Adding edges to the graph
    obj.addEdge(0, 1);
    obj.addEdge(0, 2);
    obj.addEdge(0, 3);
    obj.addEdge(0, 4);
    obj.addEdge(1, 3);
    obj.addEdge(2, 3);
    obj.addEdge(2, 4);
    obj.addEdge(2, 5);
    obj.addEdge(3, 5);
 
    // Edges added to the adjacency matrix
    Console.WriteLine("Adjacency matrix after " +
                      "edge insertions:\n");
    obj.displayAdjacencyMatrix();
 
    // Removing the edge between vertices
    // "2" and "3" from the graph
    obj.removeEdge(2, 3);
     
    // The adjacency matrix after
    // removing the edge
    Console.WriteLine("\nAdjacency matrix after " +
                      "edge removal:");
    obj.displayAdjacencyMatrix();
}
}
 
// This code is contributed by amarjeet_singh


Javascript




<script>
 
// Javascript program to add and remove edge
// in adjacency matrix representation
// of a graph
     
// Number of vertices
var n = 0;
 
// Adjacency matrix
var g = Array.from(Array(10), ()=>Array(10).fill(0));
 
// Constructor
function initialize(x)
{
    n = x;
 
    // Initializing each element of
    // the adjacency matrix to zero
    for(var i = 0; i < n; ++i)
    {
        for(var j = 0; j < n; ++j)
        {
            g[i][j] = 0;
        }
    }
}
 
// Function to display adjacency matrix
function displayAdjacencyMatrix()
{
     
    // Displaying the 2D matrix
    for(var i = 0; i < n; ++i)
    {
        document.write("<br>");
        for(var j = 0; j < n; ++j)
        {
            document.write(" " + g[i][j]);
        }
    }
}
 
// Function to update adjacency
// matrix for edge insertion
function addEdge(x, y)
{
     
    // Checks if the vertices exist
    // in the graph
    if ((x < 0) || (x >= n))
    {
        document.write(`Vertex ${x} does not exist!`);
    }
    if ((y < 0) || (y >= n))
    {
        document.write(`Vertex ${y} does not exist!`);
    }
 
    // Checks if it is a self edge
    if (x == y)
    {
        document.write("Same Vertex!<br>");
    }
     
    else
    {
         
        // Adding edge between the vertices
        g[y][x] = 1;
        g[x][y] = 1;
    }
}
 
// Function to update adjacency
// matrix for edge removal
function removeEdge(x, y)
{
     
    // Checks if the vertices exist
    // in the graph
    if ((x < 0) || (x >= n))
    {
        document.write(`Vertex ${x} does not exist!`);
    }
    if ((y < 0) || (y >= n))
    {
        document.write(`Vertex ${y} does not exist!`);
    }
 
    // Checks if it is a self edge
    if (x == y)
    {
        document.write("Same Vertex!<br>");
    }
     
    else
    {
         
        // Remove edge from between
        // the vertices
        g[y][x] = 0;
        g[x][y] = 0;
    }
}
 
 
// Driver code
// Creating an object of class Graph
initialize(6);
// Adding edges to the graph
addEdge(0, 1);
addEdge(0, 2);
addEdge(0, 3);
addEdge(0, 4);
addEdge(1, 3);
addEdge(2, 3);
addEdge(2, 4);
addEdge(2, 5);
addEdge(3, 5);
// Edges added to the adjacency matrix
document.write("Adjacency matrix after " +
                  "edge insertions:<br>");
displayAdjacencyMatrix();
// Removing the edge between vertices
// "2" and "3" from the graph
removeEdge(2, 3);
 
// The adjacency matrix after
// removing the edge
document.write("<br>Adjacency matrix after " +
                  "edge removal:<br>");
displayAdjacencyMatrix();
 
 
</script>


Output: 

Adjacency matrix after edge insertions:

 0 1 1 1 1 0
 1 0 0 1 0 0
 1 0 0 1 1 1
 1 1 1 0 0 1
 1 0 1 0 0 0
 0 0 1 1 0 0
Adjacency matrix after edge removal:

 0 1 1 1 1 0
 1 0 0 1 0 0
 1 0 0 0 1 1
 1 1 0 0 0 1
 1 0 1 0 0 0
 0 0 1 1 0 0

Time Complexity: Insertion and Deletion of an edge requires O(1) complexity while it takes O(N2) to display the adjacency matrix. 
Auxiliary Space: O(N2)



Similar Reads

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
Add and Remove Edge in Adjacency List representation of a Graph
Prerequisites: Graph and Its RepresentationIn 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: Be
8 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 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
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
Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)
We have discussed Prim's algorithm and its implementation for adjacency matrix representation of graphs. As discussed in the previous post, in Prim's algorithm, two sets are maintained, one set contains list of vertices already included in MST, other set contains vertices not yet included. In every iteration, we consider the minimum weight edge amo
9 min read
Difference between Tree edge and Back edge in graph
Tree Edge: It is an edge that is present in the tree obtained after performing DFS on the graph. All the Green edges are tree edges as shown in the below image. Back Edge: It is an edge (u, v) such that v is an ancestor of node u but not part of the DFS Traversal of the tree. Edge from 5 to 4 is a back edge. The presence of a back edge indicates a
1 min read
C program to implement Adjacency Matrix of a given Graph
Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples: Input: N = 5, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } } Ou
3 min read
C program to implement DFS traversal using Adjacency Matrix in a given Graph
Given a undirected graph with V vertices and E edges. The task is to perform DFS traversal of the graph. Examples: Input: V = 7, E = 7Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2See the diagram for connections: Output : 0 1 3 4 5 6 2Explanation: The traversal starts from 0 and follows the following path 0-1, 1-3, 1-4, 1-5, 1-6, 6-2. Input: V = 1,
3 min read
three90RightbarBannerImg