dijkstra path finding in csharp

Here's a sample implementation of Dijkstra's algorithm in C#:

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

public class Dijkstra
{
    private int GetClosestVertex(bool[] visited, int[] distances)
    {
        int minDistance = int.MaxValue;
        int closestVertex = -1;

        for (int v = 0; v < visited.Length; v++)
        {
            if (!visited[v] && distances[v] < minDistance)
            {
                minDistance = distances[v];
                closestVertex = v;
            }
        }

        return closestVertex;
    }

    public int[] ShortestPath(int[,] graph, int startIndex)
    {
        int numVertices = graph.GetLength(0);
        int[] distances = new int[numVertices];
        bool[] visited = new bool[numVertices];

        for (int i = 0; i < numVertices; i++)
        {
            distances[i] = int.MaxValue;
        }

        distances[startIndex] = 0;

        for (int i = 0; i < numVertices; i++)
        {
            int closestVertex = GetClosestVertex(visited, distances);
            visited[closestVertex] = true;

            for (int v = 0; v < numVertices; v++)
            {
                int edgeWeight = graph[closestVertex, v];

                if (edgeWeight > 0 && !visited[v])
                {
                    int distToEdge = distances[closestVertex] + edgeWeight;

                    if (distToEdge < distances[v])
                    {
                        distances[v] = distToEdge;
                    }
                }
            }
        }

        return distances;
    }
}
1506 chars
60 lines

Usage:

main.cs
int[,] graph = new int[,]
{
    { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
    { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
    { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
    { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
    { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
    { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
    { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
    { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
    { 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};

Dijkstra dijkstra = new Dijkstra();
int[] shortestDistances = dijkstra.ShortestPath(graph, 0);

Console.WriteLine(string.Join(", ", shortestDistances)); // Output: 0, 4, 12, 19, 21, 11, 9, 8, 14
547 chars
18 lines

gistlibby LogSnag