// TODO: This method should be private and should be called from the bottom of the constructor /// <summary> /// check optimality conditions: /// </summary> /// <param name="graph">The edge-weighted directed graph</param> /// <param name="sourceVertex">The source vertex to check optimality conditions from</param> private bool Check(EdgeWeightedDigraph graph, int sourceVertex) { if (graph == null) { if (LogFilter.logError) { Debug.LogErrorFormat("EdgeWeightedDigraph cannot be null"); } } if (_distanceTo[sourceVertex] != 0.0 || _edgeTo[sourceVertex] != null) { return(false); } for (int v = 0; v < graph.NumberOfVertices; v++) { if (v == sourceVertex) { continue; } if (_edgeTo[v] == null && _distanceTo[v] != double.PositiveInfinity) { return(false); } } for (int v = 0; v < graph.NumberOfVertices; v++) { foreach (DirectedEdge edge in graph.Adjacent(v)) { int w = edge.To; if (_distanceTo[v] + edge.Weight < _distanceTo[w]) { return(false); } } } for (int w = 0; w < graph.NumberOfVertices; w++) { if (_edgeTo[w] == null) { continue; } DirectedEdge edge = _edgeTo[w]; int v = edge.From; if (w != edge.To) { return(false); } if (_distanceTo[v] + edge.Weight != _distanceTo[w]) { return(false); } } return(true); }
private DijkstraShortestPath(EdgeWeightedDigraph graph, int sourceVertex, int?destinationVertex) { if (graph == null) { if (LogFilter.logError) { Debug.LogErrorFormat("EdgeWeightedDigraph cannot be null"); } } foreach (DirectedEdge edge in graph.Edges()) { if (edge.Weight < 0) { if (LogFilter.logError) { Debug.LogErrorFormat("Edge: '{0}' has negative weight", edge); } } } _distanceTo = new double[graph.NumberOfVertices]; _edgeTo = new DirectedEdge[graph.NumberOfVertices]; for (int v = 0; v < graph.NumberOfVertices; v++) { _distanceTo[v] = Double.PositiveInfinity; } _distanceTo[sourceVertex] = 0.0; _priorityQueue = new IndexMinPriorityQueue <double>(graph.NumberOfVertices); _priorityQueue.Insert(sourceVertex, _distanceTo[sourceVertex]); while (!_priorityQueue.IsEmpty()) { int v = _priorityQueue.DeleteMin(); if (destinationVertex.HasValue && v == destinationVertex.Value) { return; } foreach (DirectedEdge edge in graph.Adjacent(v)) { Relax(edge); } } Check(graph, sourceVertex); }