Adjacency Matrix in C++

An adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not – we will use the value 1 for adjacent vertices, 0 – for not adjacent.
If the graph is undirected, the adjacency matrix is symmetric.

Our class will have the following structure:

class AdjacencyMatrix {
private:
  int n;
  int **adj;
  
public:
  AdjacencyMatrix(int n) {
   this->n = n;
   adj = new int*[n];
   for (int k = 0; k < n; k++) {
     adj[k] = new int[n];
     for(int j = 0; j < n; j++) {
      adj[k][j] = 0;
     }
   }
  }
  //adding an edge
  void addEdge(int orig, int dest);
  //removing an edge
  void removeEdge(int orig, int dest);
  //printing the graph
  void display();
};

We store the matrix in a two-dimensional array, called adj.

In the code above we created a class where the constructor is taking the number of the nodes and initializes all the elements to 0. We have also defined the corresponding addEdge(), removeEdge() and display() methods.

The full source code:

#include <iostream>
using namespace std;

class AdjacencyMatrix {
    private:
        int n;
        int **adj;

    public:
        AdjacencyMatrix(int n) {
            this->n = n;
            adj = new int*[n];
            for (int k = 0; k < n; k++) {
                adj[k] = new int[n];
                for(int j = 0; j < n; j++) {
                    adj[k][j] = 0;
                }
            }
        }
        //Add a new edge to the Graph
        void addEdge(int orig, int dest) {
            if( orig > n || dest > n || orig < 1 || dest < 1) {   
                cout << "Trying to add an invalid edge";
                cout << "(" << orig << ", " << dest << ")\n";
            }
            else {
                adj[orig - 1][dest - 1] = 1;
            }
        }
          
        //remove an edge
        void removeEdge(int orig, int dest) {
            if( orig > n || dest > n || orig < 1 || dest < 1) {   
                cout << "Trying to remove an invalid edge";
                cout << "(" << orig << ", " << dest << ")\n";
            }
            else {
                adj[orig - 1][dest - 1] = 0;
            }
        }
          
        //Print the graph
        void display() {
            for(int i = 0; i < n; i++) {
                for(int j = 0; j < n; j++)
                    cout << adj[i][j] <<"  ";
                cout << endl;
            }
        }
};

int main() {
    AdjacencyMatrix M(5);
    M.addEdge(2, 5);
    M.addEdge(1, 5);
    M.addEdge(5, 1);
    M.addEdge(3, 3);
    M.removeEdge(1, 5);
      
    M.display();
      
    return 0;
}