C++ Program to Implement Adjacency Matrix


The adjacency matrix of a graph is a square matrix of size V x V. The V is the number of vertices of the graph G. In this matrix in each side V vertices are marked. If the graph has some edges from i to j vertices, then in the adjacency matrix at ith row and jth column it will be 1 (or some non-zero value for weighted graph), otherwise that place will hold 0.

The complexity of Adjacency Matrix representation:

  • The adjacency matrix representation takes O(V2) amount of space while it is computed. When graph has maximum number of edges and minimum number of edges, in both cases the required space will be same.

Input:

Output:


0
1
2
3
4
5
0
0
0
0
1
1
0
1
0
0
1
0
1
1
2
0
1
0
1
0
0
3
1
0
1
0
0
1
4
1
1
0
0
0
1
5
0
1
1
1
1
0

Algorithm

add_edge(u, v)

Input: The u and v of an edge {u,v}

Output: Adjacency matrix of the graph G

Begin
   adj_matrix[u, v] := 1
   adj_matrix[v, u] := 1
End

Example Code

#include<iostream>
using namespace std;
int vertArr[20][20]; //the adjacency matrix initially 0
int count = 0;
void displayMatrix(int v) {
   int i, j;
   for(i = 0; i < v; i++) {
      for(j = 0; j < v; j++) {
         cout << vertArr[i][j] << " ";
      }
      cout << endl;
   }
}
void add_edge(int u, int v) {       //function to add edge into the matrix
   vertArr[u][v] = 1;
   vertArr[v][u] = 1;
}
main(int argc, char* argv[]) {
   int v = 6;    //there are 6 vertices in the graph
   add_edge(0, 4);
   add_edge(0, 3);
   add_edge(1, 2);
   add_edge(1, 4);
   add_edge(1, 5);
   add_edge(2, 3);
   add_edge(2, 5);
   add_edge(5, 3);
   add_edge(5, 4);
   displayMatrix(v);
}

Output

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

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements