In C++, you can implement the shortest path algorithms like Dijkstra's and Bellman-Ford using graphs represented by adjacency lists or matrices. Below are examples of how to implement both algorithms.
Dijkstra, Bellman-Ford, shortest path, C++, graph algorithms, programming
This page provides examples of Dijkstra's and Bellman-Ford algorithms for finding the shortest path in graphs using C++. These algorithms are essential in optimizing routing and navigation systems.
// Dijkstra's Algorithm
#include
#include
#include
#include
using namespace std;
void dijkstra(int source, vector>>& graph) {
int n = graph.size();
vector dist(n, INT_MAX);
dist[source] = 0;
priority_queue, vector>, greater>> pq;
pq.push({0, source});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (auto& edge : graph[u]) {
int v = edge.first;
int weight = edge.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
for (int i = 0; i < n; ++i) {
cout << "Distance from source to " << i << " is " << dist[i] << endl;
}
}
// Bellman-Ford Algorithm
void bellman_ford(int source, vector>>& graph, int n) {
vector dist(n, INT_MAX);
dist[source] = 0;
for (int i = 1; i < n; i++) {
for (auto& edge : graph) {
int u = edge[0].first;
int v = edge[0].second.first;
int weight = edge[0].second.second;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
}
}
for (int i = 0; i < n; ++i) {
cout << "Distance from source to " << i << " is " << dist[i] << endl;
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?