Change Dijkstra's algorithm to return all shortest distances
This commit is contained in:
parent
73ead5aea7
commit
897bab12bf
@ -28,7 +28,7 @@ class WeightedEdgeGraph
|
||||
void addEdge(const int vertex1, const int vertex2, const int weight);
|
||||
int getVertexWeight(const int vertex) const;
|
||||
int getEdgeWeight(const int edge) const;
|
||||
int dijkstra(const int source, const int target) const;
|
||||
std::vector<int> dijkstra(const int source) const;
|
||||
|
||||
struct Incidence
|
||||
{
|
||||
|
@ -49,7 +49,7 @@ int WeightedEdgeGraph::getEdgeWeight(const int edge) const
|
||||
return edgeWeights_[edge];
|
||||
}
|
||||
|
||||
int WeightedEdgeGraph::dijkstra(const int source, const int target) const
|
||||
std::vector<int> WeightedEdgeGraph::dijkstra(const int source) const
|
||||
{
|
||||
std::vector<int> distances(firstVertexIncidences_.size(), std::numeric_limits<int>::max());
|
||||
auto compare = [&distances](int left, int right) { return distances[left] > distances[right]; };
|
||||
@ -63,25 +63,18 @@ int WeightedEdgeGraph::dijkstra(const int source, const int target) const
|
||||
int v{ queue.top() };
|
||||
queue.pop();
|
||||
|
||||
int incidence{ firstVertexIncidences_[v] };
|
||||
while (incidence > -1)
|
||||
for (auto neighbor = begin(v); neighbor != end(); ++neighbor)
|
||||
{
|
||||
int neighbor{ vertexEdgeIncidences_[incidence].vertex };
|
||||
int newDistance{ distances[v] + edgeWeights_[incidence >> 1] };
|
||||
if (distances[neighbor] > newDistance)
|
||||
int newDistance{ distances[v] + edgeWeights_[neighbor->edge] };
|
||||
if (distances[neighbor->vertex] > newDistance)
|
||||
{
|
||||
distances[neighbor] = newDistance;
|
||||
queue.push(neighbor);
|
||||
distances[neighbor->vertex] = newDistance;
|
||||
queue.push(neighbor->vertex);
|
||||
}
|
||||
if (neighbor == target)
|
||||
{
|
||||
return distances[target];
|
||||
}
|
||||
incidence = vertexEdgeIncidences_[incidence].next;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
return distances;
|
||||
}
|
||||
|
||||
WeightedEdgeGraph::NeighborIterator WeightedEdgeGraph::begin(const int vertex) const
|
||||
|
Loading…
x
Reference in New Issue
Block a user