An adjacency matrix is a two-dimensional matrix used to map the association between the nodes of a graph. A graph is a set of vertices (nodes) connected by edges.
In an adjacency matrix,
0
means that no association between nodes exists and1
means that an association between nodes does exist.
In the example below, we have implemented the adjacency matrix for the above illustration.
In a two-dimensional matrix, rows and columns are initialized with index
0
and so on. That’s why we have subtracted1
from each index below.
#include <iostream>using namespace std;int main() {int adjMatrix[5][5];// intializing adjMatrix to zerofor(int i = 0; i < 5 ; i++){for(int j = 0; j < 5; j++){adjMatrix[i][j] = 0;}}// setting node 1adjMatrix[1-1][2-1] = 1;adjMatrix[1-1][3-1] = 1;// setting node 2adjMatrix[2-1][1-1] = 1;adjMatrix[2-1][5-1] = 1;// setting node 3adjMatrix[3-1][1-1] = 1;adjMatrix[3-1][4-1] = 1;// setting node 4adjMatrix[4-1][3-1] = 1;adjMatrix[4-1][5-1] = 1;// setting node 5adjMatrix[5-1][2-1] = 1;adjMatrix[5-1][4-1] = 1;// printingfor(int i = 0; i < 5 ; i++){for(int j = 0; j < 5; j++){cout<< adjMatrix[i][j]<< " ";}cout<<"\n";}return 0;}
Free Resources