shortest path in csharp

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;

public class Graph
{
    private int V; // number of vertices
    private List<Tuple<int, int>>[] adj; // adjacency list

    public Graph(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>>();
        }
    }

    public void addEdge(int u, int v, int weight)
    {
        adj[u].Add(new Tuple<int, int>(v, weight));
        adj[v].Add(new Tuple<int, int>(u, weight));
    }

    public int[] shortestPath(int start)
    {
        int[] dist = new int[V]; // array to store shortest distances
        bool[] visited = new bool[V]; // array to mark visited vertices

        // initialize distances to infinity and visited to false
        for (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 vertex
            if (visited[curr.Item1])
            {
                continue;
            }

            // mark vertex as visited
            visited[curr.Item1] = true;

            // update distances to its neighbors
            foreach (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 distances
        return dist;
    }
}

// example usage
Graph 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 distances
for (int i = 0; i < shortestDistances.Length; i++)
{
    Console.WriteLine("Shortest distance from vertex 0 to vertex {0}: {1}", i, shortestDistances[i]);
}
2556 chars
93 lines

gistlibby LogSnag