How do I implement shortest path (Dijkstra/Bellman-Ford) in C++?

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; } }

Dijkstra Bellman-Ford shortest path C++ graph algorithms programming