Wednesday 22 November 2017

C++ Program to Describe the Representation of Graph using Adjacency Matrix


Code:

#include   iostream
#include   iomanip

using namespace std;

// A function to print the adjacency matrix.
void PrintMat(int mat[][20], int n)
{
int i, j;

cout<<"\n\n"<
for(i = 0; i < n; i++)
cout<
cout<<"\n\n";

// Print 1 if the corresponding vertexes are connected otherwise 0.
for(i = 0; i < n; i++)
{
cout<
for(j = 0; j < n; j++)
{
cout<
}
cout<<"\n\n";
}
}

int main()
{
int i, j, v;

cout<<"Enter the number of vertexes: ";
cin>>v;

int  mat[20][20];

cout<<"\n";
// Take input of the adjacency of each pair of vertexes.
for(i = 0; i < v; i++)
{
for(j = i; j < v; j++)
{
if(i != j)
{
cout<<"Enter 1 if the vertex "<
cin>>mat[i][j];

mat[j][i] = mat[i][j];
}
else
mat[i][j] = 0;
}
}

PrintMat(mat, v);
}


Output:

Case 1:
Enter the number of vertexes: 4

Enter 1 if the vertex 1 is adjacent to 2, otherwise 0: 1
Enter 1 if the vertex 1 is adjacent to 3, otherwise 0: 0
Enter 1 if the vertex 1 is adjacent to 4, otherwise 0: 1
Enter 1 if the vertex 2 is adjacent to 3, otherwise 0: 0
Enter 1 if the vertex 2 is adjacent to 4, otherwise 0: 1
Enter 1 if the vertex 3 is adjacent to 4, otherwise 0: 0


      (1)  (2)  (3)  (4)

  (1)   0   1   0   1

  (2)   1   0   0   1

  (3)   0   0   0   0

  (4)   1   1   0   0

Case 2:
Enter the number of vertexes: 3

Enter 1 if the vertex 1 is adjacent to 2, otherwise 0: 1
Enter 1 if the vertex 1 is adjacent to 3, otherwise 0: 0
Enter 1 if the vertex 2 is adjacent to 3, otherwise 0: 1


      (1)  (2)  (3)

  (1)   0   1   0

  (2)   1   0   1

  (3)   0   1   0



More C++ Programs:












100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...