void dijkstra(Graph graph) { initDijkstra(graph); DijkstraElement actual = dijkstraElements[origin.Id - 1]; while (unvisitedVertices > 0 && actual != null) { updateDistances(actual.Vertex); //Get next actual actual = getShortestElement(); } //TODO What is it with the not conected graphs }
//Sets initial vertex with propper info void initDijkstra(Graph graph) { foreach (Vertex v in graph.Vertices) { DijkstraElement element = new DijkstraElement(v); // ShortestElement sE = new ShortestElement(element); //Initial if (v == origin) { element.ShortestDistance = 0; element.IsDefinitive = true; } dijkstraElements.Add(element); } unvisitedVertices = dijkstraElements.Count - 1; //-1 Start Vertex }
void updateDistances(Vertex actual) { double newValue; DijkstraElement startVertex = dijkstraElements[actual.Id - 1]; //DijkstraElement of startVertex DijkstraElement nextVertex; foreach (Edge e in actual.Edges) { nextVertex = dijkstraElements[e.Destination.Id - 1]; if (!nextVertex.IsDefinitive) //If not definitive: Update weights { newValue = startVertex.ShortestDistance + e.Weight; if (newValue < nextVertex.ShortestDistance) //Update { nextVertex.ShortestDistance = newValue; nextVertex.ComingFrom = actual; } } } }
//Not using priority Queue DijkstraElement getShortestElement() { double shortestDistance = double.PositiveInfinity; DijkstraElement shortestElement = null; foreach (DijkstraElement d in dijkstraElements) { if (!d.IsDefinitive) { if (d.ShortestDistance < shortestDistance) { shortestElement = d; shortestDistance = d.ShortestDistance; } } } if (shortestElement != null) { shortestElement.IsDefinitive = true; } unvisitedVertices--; return(shortestElement); }