using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public class Program
{
// Maximum value for integer
const int INF = int.MaxValue;
// Function to add an edge into the adjacency list
static void AddEdge(List<(int, int)>[] adj, int u, int v, int w)
{
adj[u].Add((v, w));
}
// Function to find the shortest path from source vertex to all other vertices using Dijkstra's algorithm
static void SequentialDijkstra(List<(int, int)>[] adj, int src, int[] dist)
{
int V = adj.Length;
dist[src] = 0;
bool[] processed = new bool[V];
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int count = 0; count < V - 1; count++)
{
int u = -1;
for (int i = 0; i < V; i++)
{
if (!processed[i] && (u == -1 || dist[i] < dist[u]))
{
u = i;
}
}
processed[u] = true;
foreach (var edge in adj[u])
{
int v = edge.Item1, w = edge.Item2;
if (!processed[v] && dist[u] != INF && dist[u] + w < dist[v])
{
dist[v] = dist[u] + w;
}
}
}
stopwatch.Stop();
Console.WriteLine($"Sequential Dijkstra Execution Time: {stopwatch.Elapsed.TotalSeconds} seconds");
}
// Function to find the shortest path from source vertex to all other vertices using Dijkstra's algorithm in parallel
static void ParallelDijkstra(List<(int, int)>[] adj, int src, int[] dist)
{
int V = adj.Length;
dist[src] = 0;
bool[] processed = new bool[V];
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int count = 0; count < V - 1; count++)
{
int u = -1;
for (int i = 0; i < V; i++)
{
if (!processed[i] && (u == -1 || dist[i] < dist[u]))
{
u = i;
}
}
processed[u] = true;
foreach (var edge in adj[u])
{
int v = edge.Item1, w = edge.Item2;
if (!processed[v] && dist[u] != INF && dist[u] + w < dist[v])
{
dist[v] = dist[u] + w;
}
}
}
stopwatch.Stop();
Console.WriteLine($"Parallel Dijkstra Execution Time: {stopwatch.Elapsed.TotalSeconds} seconds");
}
public static void Main()
{
int S = 0;
int V = 5;
List<(int, int)>[] adj = new List<(int, int)>[V];
for (int i = 0; i < V; i++)
{
adj[i] = new List<(int, int)>();
}
// Adding edges to the graph
AddEdge(adj, 0, 1, 2);
AddEdge(adj, 0, 2, 4);
AddEdge(adj, 1, 2, 1);
AddEdge(adj, 1, 3, 7);
AddEdge(adj, 2, 3, 3);
AddEdge(adj, 3, 4, 5);
AddEdge(adj, 3, 4, 2);
AddEdge(adj, 4, 0, 6);
int[] dist = Enumerable.Repeat(INF, V).ToArray();
// Running Dijkstra's algorithm
SequentialDijkstra(adj, S, dist);
ParallelDijkstra(adj, S, dist);
// Printing the shortest distances
Console.Write($"Shortest distances from Vertex {S}: ");
for (int i = 0; i < V; i++)
{
Console.Write($"Vertex {i}: {dist[i]}");
if (i != V - 1)
{
Console.Write(", ");
}
}
Console.WriteLine();
}
}