-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphrepres.cpp
More file actions
118 lines (100 loc) · 2.86 KB
/
graphrepres.cpp
File metadata and controls
118 lines (100 loc) · 2.86 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
using namespace std;
class Graph {
private:
int vertices; // Number of vertices
int** adjMatrix; // Adjacency matrix
struct Node {
int vertex;
Node* next;
};
Node** adjList; // Adjacency list (array of linked lists)
public:
// Constructor
Graph(int v) {
vertices = v;
// Initialize adjacency matrix
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; // Initialize all values to 0
}
}
// Initialize adjacency list
adjList = new Node*[vertices];
for (int i = 0; i < vertices; i++) {
adjList[i] = nullptr; // Start with empty linked lists
}
}
// Add an edge (undirected graph)
void addEdge(int u, int v) {
// Update adjacency matrix
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1; // For undirected graph
// Update adjacency list
Node* newNode1 = new Node{v, adjList[u]};
adjList[u] = newNode1;
Node* newNode2 = new Node{u, adjList[v]};
adjList[v] = newNode2;
}
// Display adjacency matrix
void displayAdjMatrix() {
cout << "Adjacency Matrix:\n";
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
// Display adjacency list
void displayAdjList() {
cout << "Adjacency List:\n";
for (int i = 0; i < vertices; i++) {
cout << i << ": ";
Node* temp = adjList[i];
while (temp != nullptr) {
cout << temp->vertex << " ";
temp = temp->next;
}
cout << endl;
}
}
// Destructor to free memory
~Graph() {
// Free adjacency matrix
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
// Free adjacency list
for (int i = 0; i < vertices; i++) {
Node* temp = adjList[i];
while (temp != nullptr) {
Node* toDelete = temp;
temp = temp->next;
delete toDelete;
}
}
delete[] adjList;
}
};
int main() {
int vertices, edges;
cout << "Enter the number of vertices: ";
cin >> vertices;
Graph graph(vertices);
cout << "Enter the number of edges: ";
cin >> edges;
cout << "Enter the edges (u v):\n";
for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;
graph.addEdge(u, v);
}
// Display adjacency matrix and list
graph.displayAdjMatrix();
graph.displayAdjList();
return 0;
}