Here is my code for implementing Graph using adjacency matrix. The code should be Object-oriented and there is a method isPath() checking if there is a connection between two nodes. Some advice?
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
class Graph
{
protected:
int value;
int **graphm;
public:
Graph(int value)
{
this->value = value;
graphm = new int*[value];
int k, j;
for (k = 0; k < value; k++)
{
graphm[k] = new int[value];
for (j = 0; j < value; j++)
{
graphm[k][j] = 0;
}
}
}
void newEdge(int head, int end)
{
if (head > value || end > value || head < 0 || end < 0)
{
cout << "Invalid edge!\n";
}
else
{
graphm[head - 1][end - 1] = 1;
graphm[end - 1][head - 1] = 1;
}
}
void display()
{
int i, p;
for (i = 0; i < value; i++)
{
for (p = 0; p < value; p++)
{
cout << graphm[i][p] << " ";
}
cout << endl;
}
}
void isPath(int head, int end)
{
int k, o;
ofstream fullstore("Test.txt");
cout << graphm[head - 1][end - 1];
cout << endl;
if (!fullstore.is_open())
{
cout << "File can't be open";
}
if (graphm[head - 1][end - 1] == 1)
{
cout << "There is an edge between " << head << " and " << end << "\n";
fullstore << head << ", " << end;
fullstore.close();
}
else
{
cout << "Edge not found\n";
}
}
};
int main()
{
int vertex, numberOfEdges, i, head, end;
cout << "Enter number of nodes: ";
cin >> vertex;
numberOfEdges = vertex * (vertex - 1);
Graph g1(vertex);
for (int i = 0; i < numberOfEdges; i++)
{
cout << "Enter edge ex.1 2 (-1 -1 to exit): \n";
cin >> head >> end;
if ((head == -1) && (end == -1))
{
break;
}
g1.newEdge(head, end);
}
g1.display();
cout << endl;
g1.isPath(1, 3);
return 0;
}