-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadjmatrix.cpp
More file actions
76 lines (63 loc) · 1.82 KB
/
adjmatrix.cpp
File metadata and controls
76 lines (63 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
using namespace std;
class Graph {
int **adjMatrix;
int vertices;
public:
void createGraph(int v, int e) {
if (v <= 0) {
cout << "Number of vertices must be positive.\n";
return;
}
vertices = v;
adjMatrix = new int*[vertices];
for (int i = 0; i < vertices; i++) {
adjMatrix[i] = new int[vertices];
for (int j = 0; j < vertices; j++) {
adjMatrix[i][j] = 0;
}
}
int u, ver;
for (int i = 0; i < e; i++) {
cout << "Enter edge " << i + 1 << " (format: u v): ";
cin >> u >> ver;
// Check for valid input
if (u < 0 || u >= vertices || ver < 0 || ver >= vertices) {
cout << "Invalid edge! Vertex numbers should be between 0 and " << vertices - 1 << ".\n";
i--; // Repeat this iteration
continue;
}
adjMatrix[u][ver] = 1;
adjMatrix[ver][u] = 1; // Remove for directed graph
}
}
void displayGraph() {
if (vertices <= 0) return; // No graph to display
cout << "Adjacency Matrix:\n";
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
void deleteGraph() {
if (vertices <= 0) return; // No need to delete
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
}
};
int main() {
Graph g;
int v, e;
cout << "Enter number of vertices: ";
cin >> v;
cout << "Enter number of edges: ";
cin >> e;
g.createGraph(v, e);
g.displayGraph();
g.deleteGraph();
return 0;
}