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);
|
void addEdge(const int vertex1, const int vertex2, const int weight);
|
||||||
int getVertexWeight(const int vertex) const;
|
int getVertexWeight(const int vertex) const;
|
||||||
int getEdgeWeight(const int edge) 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
|
struct Incidence
|
||||||
{
|
{
|
||||||
|
@ -49,7 +49,7 @@ int WeightedEdgeGraph::getEdgeWeight(const int edge) const
|
|||||||
return edgeWeights_[edge];
|
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());
|
std::vector<int> distances(firstVertexIncidences_.size(), std::numeric_limits<int>::max());
|
||||||
auto compare = [&distances](int left, int right) { return distances[left] > distances[right]; };
|
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() };
|
int v{ queue.top() };
|
||||||
queue.pop();
|
queue.pop();
|
||||||
|
|
||||||
int incidence{ firstVertexIncidences_[v] };
|
for (auto neighbor = begin(v); neighbor != end(); ++neighbor)
|
||||||
while (incidence > -1)
|
|
||||||
{
|
{
|
||||||
int neighbor{ vertexEdgeIncidences_[incidence].vertex };
|
int newDistance{ distances[v] + edgeWeights_[neighbor->edge] };
|
||||||
int newDistance{ distances[v] + edgeWeights_[incidence >> 1] };
|
if (distances[neighbor->vertex] > newDistance)
|
||||||
if (distances[neighbor] > newDistance)
|
|
||||||
{
|
{
|
||||||
distances[neighbor] = newDistance;
|
distances[neighbor->vertex] = newDistance;
|
||||||
queue.push(neighbor);
|
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
|
WeightedEdgeGraph::NeighborIterator WeightedEdgeGraph::begin(const int vertex) const
|
||||||
|
Loading…
x
Reference in New Issue
Block a user