Dijkstra Algorithm using OpenMP
#include <iostream>
#include <limits.h>
#include <omp.h>
#include <chrono>
#define INF INT_MAX
#define V 6 // Number of vertices
using namespace std;
using namespace chrono;
// Function to find the vertex with the minimum distance
int min_distance(int dist[], int visited[]) {
int min = INF, min_index = -1;
#pragma omp parallel for reduction(min:min_index)
for (int i = 0; i < V; i++) {
if (!visited[i] && dist[i] <= min) {
min = dist[i];
min_index = i;
}
}
return min_index;
}
// Dijkstra's algorithm using OpenMP
void dijkstra(int graph[V][V], int src) {
int dist[V]; // dist[i] stores the shortest distance from src to i
int visited[V] = {0}; // visited[i] will be 1 if vertex i is included in the shortest
path
// Initialize distances
for (int i = 0; i < V; i++) {
dist[i] = INF;
}
dist[src] = 0;
// Find the shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Find the vertex with the minimum distance from the set of vertices not yet
processed
int u = min_distance(dist, visited);
// Mark the selected vertex as processed
visited[u] = 1;
// Update the distance values of the adjacent vertices of the selected vertex
#pragma omp parallel for
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + graph[u][v]
< dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
// Print the shortest distances
cout << "Vertex Distance from Source" << endl;
for (int i = 0; i < V; i++) {
cout << i << " \t\t " << dist[i] << endl;
}
}
int main() {
// Adjacency matrix representation of a graph
int graph[V][V] = {
{0, 9, 0, 0, 0, 14},
{9, 0, 10, 0, 0, 0},
{0, 10, 0, 11, 0, 0},
{0, 0, 11, 0, 6, 0},
{0, 0, 0, 6, 0, 9},
{14, 0, 0, 0, 9, 0}
};
int source = 0; // Starting node
auto start_parallel = high_resolution_clock::now();
dijkstra(graph, source);
auto end_parallel = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(end_parallel - start_parallel);
cout << "\nTime Taken: " << duration.count() << " milliseconds" << endl;
return 0;
}
OutPut