-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadj&visited.cpp
More file actions
92 lines (76 loc) · 2.33 KB
/
adj&visited.cpp
File metadata and controls
92 lines (76 loc) · 2.33 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
#include <iostream>
using namespace std;
class Graph {
int **adjMatrix;
int vertices;
public:
void createGraph(int v, int e) {
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; // Initialize adjacency matrix with 0
}
}
int u, ver;
for (int i = 0; i < e; i++) {
cout << "Enter edge " << i + 1 << " (format: u v): ";
cin >> u >> ver;
if (u < 0 || u >= vertices || ver < 0 || ver >= vertices) {
cout << "Invalid edge! Vertex numbers should be between 0 and " << vertices - 1 << ".\n";
i--;
continue;
}
adjMatrix[u][ver] = 1;
adjMatrix[ver][u] = 1; // Remove this line for a directed graph
}
}
bool isVisited(int vertex) {
if (vertex < 0 || vertex >= vertices) {
cout << "Invalid vertex number!\n";
return false;
}
// Check if the vertex has at least one connection (row or column has a 1)
for (int i = 0; i < vertices; i++) {
if (adjMatrix[vertex][i] == 1 || adjMatrix[i][vertex] == 1) {
return true;
}
}
return false;
}
void checkVisited() {
int vertex;
cout << "Enter a vertex to check if visited: ";
cin >> vertex;
if (isVisited(vertex)) {
cout << "Vertex " << vertex << " has been visited (it is connected to another vertex).\n";
} else {
cout << "Vertex " << vertex << " has NOT been visited (it is isolated).\n";
}
}
void deleteGraph() {
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);
while (true) {
g.checkVisited();
char choice;
cout << "Do you want to check another vertex? (y/n): ";
cin >> choice;
if (choice != 'y' && choice != 'Y') break;
}
g.deleteGraph();
return 0;
}