-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhpc1.txt
122 lines (100 loc) · 3.25 KB
/
hpc1.txt
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
119
120
121
122
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <omp.h>
using namespace std;
// Graph class representing an undirected graph using adjacency list representation
class Graph {
private:
int numVertices; // Number of vertices
vector<vector<int>> adj; // Adjacency list
public:
Graph(int vertices) : numVertices(vertices), adj(vertices) {}
// Add an edge between two vertices
void addEdge(int src, int dest) {
adj[src].push_back(dest);
adj[dest].push_back(src);
}
// View the graph
void viewGraph() {
cout << "Graph:\n";
for (int i = 0; i < numVertices; i++) {
cout << "Vertex " << i << " -> ";
for (int neighbor : adj[i]) {
cout << neighbor << " ";
}
cout << endl;
}
}
// Perform Breadth First Search (BFS) in parallel
void bfs(int startVertex) {
vector<bool> visited(numVertices, false);
queue<int> q;
// Mark the start vertex as visited and enqueue it
visited[startVertex] = true;
q.push(startVertex);
while (!q.empty()) {
int currentVertex = q.front();
q.pop();
cout << currentVertex << " ";
// Enqueue all adjacent unvisited vertices
#pragma omp parallel for
for (int neighbor : adj[currentVertex]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
// Perform Depth First Search (DFS) in parallel
void dfs(int startVertex) {
vector<bool> visited(numVertices, false);
stack<int> s;
// Mark the start vertex as visited and push it onto the stack
visited[startVertex] = true;
s.push(startVertex);
while (!s.empty()) {
int currentVertex = s.top();
s.pop();
cout << currentVertex << " ";
// Push all adjacent unvisited vertices onto the stack
#pragma omp parallel for
for (int neighbor : adj[currentVertex]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
s.push(neighbor);
}
}
}
}
};
int main() {
int numVertices;
cout << "Enter the number of vertices in the graph: ";
cin >> numVertices;
// Create a graph with the specified number of vertices
Graph graph(numVertices);
int numEdges;
cout << "Enter the number of edges in the graph: ";
cin >> numEdges;
cout << "Enter the edges (source destination):\n";
for (int i = 0; i < numEdges; i++) {
int src, dest;
cin >> src >> dest;
graph.addEdge(src, dest);
}
// View the graph
graph.viewGraph();
int startVertex;
cout << "Enter the starting vertex for BFS and DFS: ";
cin >> startVertex;
cout << "Breadth First Search (BFS): ";
graph.bfs(startVertex);
cout << endl;
cout << "Depth First Search (DFS): ";
graph.dfs(startVertex);
cout << endl;
return 0;
}