The Code given below can be used in TURBO C++ Compilers: -
#include <iostream.h>
#include<conio.h>
#include <stdio.h>
#include <string.h>
int adj[10][10];
int n; // no of vertices
int main()
{
clrscr();
int i, gType, maxEdge, origin, dest;
cout << "Enter the type of graph:\n"
<< "1.Undirected\n2.Directed\n";
cin >> gType;
cout << "Enter the number of vertices: ";
cin >> n;
switch (gType)
{
case 1:
{
maxEdge = n * (n - 1) / 2;
break;
}
case 2:
{
maxEdge = n * (n - 1);
break;
}
}
for (i = 0; i <= maxEdge; i++)
{
cout << "Enter edge " << i << " [row column]: ";
cin >> origin >> dest;
if (origin == -1 && dest == -1)
{
break;
}
if (origin >= n || dest >= n || origin < 0 || dest < 0)
{
cout << "\nInvalid vertex!\n";
i--;
}
else
{
adj[origin][dest] = 1;
if (gType == 1)
{
adj[dest][origin] = 1; // for undirected graph
}
}
}
cout << "The adjacency matrix for the provided graph:\n";
for (i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << adj[i][j] << " ";
}
cout << endl;
}
getch();
return 0;
}
The Code given below can be used in gcc/g++ Compilers: -
#include <iostream>
using namespace std;
int adj[10][10];
int n; // no of vertices
int main()
{
int gType, maxEdge, origin, dest;
cout << "Enter the type of graph:\n" << "1.Undirected\n2.Directed\n";
cin >> gType;
cout << "Enter the number of vertices: ";
cin >> n;
switch (gType)
{
case 1:
{
maxEdge = n * (n - 1) / 2;
break;
}
case 2:
{
maxEdge = n * (n - 1);
break;
}
}
for (int i = 0; i <= maxEdge; i++)
{
cout << "Enter edge " << i << " [row column]: ";
cin >> origin >> dest;
if (origin == -1 && dest == -1)
break;
if (origin >= n || dest >= n || origin < 0 || dest < 0)
{
cout << "\nInvalid vertex!\n";
i--;
}
else
{
adj[origin][dest] = 1;
if (gType == 1)
{
adj[dest][origin] = 1; // for undirected graph
}
}
}
cout << "The adjacency matrix for the provided graph:\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << adj[i][j] << " ";
}
cout << endl;
}
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP