dijkstra algorithm in csharp

Here's an implementation of Dijkstra's algorithm in C#:

main.cs
using System;
using System.Collections.Generic;

public class Dijkstra
{
    private static int V;
    private static int[,] graph;
 
    private int minDistance(int[] dist, bool[] sptSet)
    {
        int min = int.MaxValue, min_index = -1;
 
        for (int v = 0; v < V; v++)
            if (sptSet[v] == false && dist[v] <= min)
            {
                min = dist[v];
                min_index = v;
            }
 
        return min_index;
    }
 
    private void printSolution(int[] dist)
    {
        Console.WriteLine("Vertex \t Distance from Source");
        for (int i = 0; i < V; i++)
            Console.WriteLine(i + " \t\t " + dist[i]);
    }
 
    public void dijkstra(int[,] graph, int src)
    {
        V = graph.GetLength(0);
        int[] dist = new int[V]; 
        bool[] sptSet = new bool[V];

        for (int i = 0; i < V; i++)
        {
            dist[i] = int.MaxValue;
            sptSet[i] = false;
        }
 
        dist[src] = 0;
 
        for (int count = 0; count < V - 1; count++)
        {
            int u = minDistance(dist, sptSet);
 
            sptSet[u] = true;

            for (int v = 0; v < V; v++)
 
                if (!sptSet[v] && graph[u,v] != 0 && dist[u] != int.MaxValue &&
                     dist[u]+graph[u,v] < dist[v])
                    dist[v] = dist[u] + graph[u,v];
        }
 
        printSolution(dist);
    }

    static void Main(string[] args)
    {
        graph = new int[,] {{0, 2, 0, 6, 0},
                     {2, 0, 3, 8, 5},
                     {0, 3, 0, 0, 7},
                     {6, 8, 0, 0, 9},
                     {0, 5, 7, 9, 0}};
        Dijkstra t = new Dijkstra();
        t.dijkstra(graph, 0);

        Console.ReadKey();
    }
}
1736 chars
73 lines

Note that in this implementation, the graph is represented as a 2D array, where graph[i,j] represents the weight of the edge between node i and node j. In this example, 0 represents no edge between nodes.

Also, the main function simply creates a sample graph and runs the algorithm on it. In practice, you would likely want to read the graph data from a file or other source.

gistlibby LogSnag