#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>
#define MAX_VERTICES 100
struct Node {
int vertex;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node* adjLists[MAX_VERTICES];
int* visited;
};
struct Node* createNode(int v) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int n) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = n;
graph->visited = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void parallelDFS(struct Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);
#pragma omp parallel
{
#pragma omp single nowait
{
#pragma omp taskloop grainsize(4) shared(graph)
for (int i = 0; i < graph->numVertices; ++i) {
if (graph->visited[i] == 0) {
parallelDFS(graph, i);
}
}
}
}
}
void DFS(struct Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);
for (int i = 0; i < graph->numVertices; ++i) {
if (graph->visited[i] == 0) {
parallelDFS(graph, i);
}
}
}
int main() {
int numVertices, numEdges;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
struct Graph* graph_parallel = createGraph(numVertices);
struct Graph* graph = createGraph(numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);
printf("Enter the edges (source destination):\n");
for (int i = 0; i < numEdges; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
addEdge(graph_parallel, src, dest);
}
printf("Depth First Traversal (Sequential):\n");
clock_t start_time = clock();
DFS(graph, 0);
printf("\n");
clock_t end_time = clock();
double duration = ((double)(end_time - start_time)) / CLOCKS_PER_SEC;
printf("\nTime taken: %lf seconds\n\n", duration);
printf("Depth First Traversal (Parallel):\n");
clock_t start_time_parallel = clock();
parallelDFS(graph_parallel , 0);
printf("\n");
clock_t end_time_parallel = clock();
double duration_parallel = ((double)(end_time_parallel - start_time_parallel)) / CLOCKS_PER_SEC;
printf("\nTime taken: %lf seconds\n", duration_parallel);
return 0;
}