/// <summary>Finds the minimum paths from the <see cref="Vertex"/> with the specified id to all the other <see cref="Vertices"/> of the graph.</summary> /// <param name="sourceId">The id of the source <see cref="Vertex"/>.</param> /// <exception cref="ArgumentNullException"></exception> public void FindMinimumPathsFrom(string sourceId) { if (sourceId == null) { throw new ArgumentNullException("sourceId"); } foreach (DijkstraVertex vtx in Vertices) { vtx.PathInformation.SetDefaultValues(); if (vtx.Vertex.Id == sourceId) { vtx.PathInformation.MinimumCost = 0; } } BuildMinHeap(); while (HeapSize > 0) { DijkstraVertex min = ExtractMin(); foreach (NavigableNeighbor nn in min.Vertex.Neighbors) { Relax(min, nn.Neighbor, nn.Cost, nn.ConnectingEdge); } } }
private void MinHeapify(int i) { int left = 2 * i + 1; int right = left + 1; int min; if (left < HeapSize && Vertices[left] < Vertices[i]) { min = left; } else { min = i; } if (right < HeapSize && Vertices[right] < Vertices[min]) { min = right; } if (min != i) { DijkstraVertex swap = Vertices[i]; Vertices[i] = Vertices[min]; Vertices[min] = swap; MinHeapify(min); } }
private void Relax(DijkstraVertex source, Vertex target, double cost, Edge connectingEdge) { DijkstraVertex trg = Array.Find(Vertices, v => v.Vertex.Id == target.Id); if (trg.PathInformation.MinimumCost > source.PathInformation.MinimumCost + cost) { trg.PathInformation.MinimumCost = source.PathInformation.MinimumCost + cost; trg.PathInformation.Predecessor = source; trg.PathInformation.ConnectingEdge = connectingEdge; } }
private DijkstraVertex ExtractMin() { DijkstraVertex min = Vertices[0]; Vertices[0] = Vertices[HeapSize - 1]; Vertices[HeapSize - 1] = min; HeapSize--; MinHeapify(0); return(min); }
/// <summary>This constructor initializes the new <c>DijkstraAlgorithm</c> from an array containing all the <see cref="Vertex"/>-s of the <see cref="GraphParser"/>.</summary> /// <param name="vertices">The <see cref="Vertex"/>-s of the <see cref="GraphParser"/>.</param> /// <exception cref="ArgumentNullException"></exception> public DijkstraAlgorithm(Vertex[] vertices) { if (vertices == null) { throw new ArgumentNullException("vertices"); } Vertices = new DijkstraVertex[vertices.Length]; for (int i = 0; i < Vertices.Length; i++) { Vertices[i] = new DijkstraVertex(vertices[i]); } HeapSize = Vertices.Length; }