using System.Collections.Generic;
public static class DijkstraWithoutQueue
public static List<int> DijkstraAlgorithm(int[,] graph, int sourceNode, int destinationNode)
var n = graph.GetLength(0);
var distance = new int[n];
for (int i = 0; i < n; i++)
distance[i] = int.MaxValue;
distance[sourceNode] = 0;
var previous = new int?[n];
var minDistance = int.MaxValue;
for (int i = 0; i < n; i++)
if (!used[i] && minDistance > distance[i])
minDistance = distance[i];
if (minDistance == int.MaxValue)
for (int i = 0; i < n; i++)
if (graph[minNode, i] > 0)
var shortestToMinNode = distance[minNode];
var distanceToNextNode = graph[minNode, i];
var totalDistance = shortestToMinNode + distanceToNextNode;
if (totalDistance < distance[i])
distance[i] = totalDistance;
if (distance[destinationNode] == int.MaxValue)
var path = new LinkedList<int>();
int? currentNode = destinationNode;
while (currentNode != null)
path.AddFirst(currentNode.Value);
currentNode = previous[currentNode.Value];
public static void Main()
{ 0, 0, 0, 0, 0, 0, 10, 0, 12, 0, 0, 0 },
{ 0, 0, 0, 0, 20, 0, 0, 26, 0, 5, 0, 6 },
{ 0, 0, 0, 0, 0, 0, 0, 15, 14, 0, 0, 9 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0 },
{ 0, 20, 0, 0, 0, 5, 17, 0, 0, 0, 0, 11 },
{ 0, 0, 0, 0, 5, 0, 6, 0, 3, 0, 0, 33 },
{10, 0, 0, 0, 17, 6, 0, 0, 0, 0, 0, 0 },
{ 0, 26, 15, 0, 0, 0, 0, 0, 0, 3, 0, 20 },
{12, 0, 14, 0, 0, 3, 0, 0, 0, 0, 0, 0 },
{ 0, 5, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0 },
{ 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 6, 9, 0, 11, 33, 0, 20, 0, 0, 0, 0 },
public static void PrintPath(int[,] graph, int sourceNode, int destinationNode)
"Shortest path [{0} -> {1}]: ",
var path = DijkstraWithoutQueue.DijkstraAlgorithm(graph, sourceNode, destinationNode);
Console.WriteLine("no path");
for (int i = 0; i < path.Count - 1; i++)
pathLength += graph[path[i], path[i + 1]];
var formattedPath = string.Join("->", path);
Console.WriteLine("{0} (length {1})", formattedPath, pathLength);