To find the shortest path between two vertices in a graph, Dijkstra's algorithm can be used. Here's an example implementation in C# using a priority queue to efficiently select the next vertex to visit:
main.cs
using System;
using System.Collections.Generic;
publicclassGraph{
privateint V; // number of verticesprivate List<Tuple<int, int>>[] adj; // adjacency listpublicGraph(int numVertices) {
V = numVertices;
adj = new List<Tuple<int, int>>[numVertices];
for (int i = 0; i < numVertices; i++)
{
adj[i] = new List<Tuple<int, int>>();
}
}
publicvoidaddEdge(int u, int v, int weight) {
adj[u].Add(new Tuple<int, int>(v, weight));
adj[v].Add(new Tuple<int, int>(u, weight));
}
publicint[] shortestPath(int start) {
int[] dist = newint[V]; // array to store shortest distancesbool[] visited = newbool[V]; // array to mark visited vertices// initialize distances to infinity and visited to falsefor (int i = 0; i < V; i++)
{
dist[i] = int.MaxValue;
visited[i] = false;
}
// distance to starting vertex is 0 dist[start] = 0;
// create a priority queue to store vertices to visit PriorityQueue<Tuple<int, int>> pq = new PriorityQueue<Tuple<int, int>>();
// add starting vertex to the queue pq.Enqueue(new Tuple<int, int>(start, 0));
while (pq.Count > 0)
{
// get the next vertex to visit Tuple<int, int> curr = pq.Dequeue();
// if it has already been visited, continue to the next vertexif (visited[curr.Item1])
{
continue;
}
// mark vertex as visited visited[curr.Item1] = true;
// update distances to its neighborsforeach (Tuple<int, int> neighbor in adj[curr.Item1])
{
int newDist = dist[curr.Item1] + neighbor.Item2;
if (newDist < dist[neighbor.Item1])
{
dist[neighbor.Item1] = newDist;
pq.Enqueue(new Tuple<int, int>(neighbor.Item1, newDist));
}
}
}
// return array of shortest distancesreturn dist;
}
}
// example usageGraph g = new Graph(5);
g.addEdge(0, 1, 5);
g.addEdge(0, 2, 1);
g.addEdge(2, 1, 2);
g.addEdge(2, 3, 7);
g.addEdge(1, 4, 4);
g.addEdge(3, 4, 3);
int[] shortestDistances = g.shortestPath(0);
// print shortest distancesfor (int i = 0; i < shortestDistances.Length; i++)
{
Console.WriteLine("Shortest distance from vertex 0 to vertex {0}: {1}", i, shortestDistances[i]);
}