private void InitializeGraph(int V) { this.Vertices = V; AdjacencyList = new LinkedListofGraphNodes[Vertices]; for (int i = 0; i < V; i++) { AdjacencyList[i] = new LinkedListofGraphNodes(); } }
public void DijkstraAlgorithm(int sourceVertex) { MinHeap minHeap = new MinHeap(Vertices); int[] distanceTable = new int[Vertices]; //Set all distances to max value initially for (int i = 0; i < distanceTable.Length; i++) { distanceTable[i] = Int32.MaxValue; } //Set source vertex's distance as 0; minHeap.DecreaseKey(sourceVertex, 0); distanceTable[sourceVertex] = 0; while (minHeap.HeapSize > 0) { //Extract min MinHeapNode minNode = minHeap.ExtractMin(); Console.WriteLine("Min value extraxted: " + minNode.Vertex); //Look for the node's neighbors in adjacency list LinkedListofGraphNodes neighbors = AdjacencyList[minNode.Vertex]; GraphNode p = neighbors.Head; while (p != null) { if (minHeap.IsinMinHeap(p.Key) && minNode.Distance != Int32.MaxValue) { int new_distance = minNode.Distance + p.EdgeWeight; if (distanceTable[p.Key] > new_distance) { minHeap.DecreaseKey(p.Key, new_distance); distanceTable[p.Key] = new_distance; } } p = p.Next; } } PrintDistanceTable(distanceTable); }