C++ · Solution

Shortest Path

This C++ solution uses graph traversal for Shortest Path. Read the reasoning, inspect the code, or try your own test case below.

Graphs & treesGraph traversalC++34 lines
Solution187of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Shortest Path: traverse the graph recursively or with an explicit stack, carrying the information needed for each component, path, or subtree.

Depth-first searchGraphs

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

shortest_path.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    vector<int> bellman_ford(int v, vector<vector<int>>& edge, int src){
        vector<int> dist(v + 1, 1e8);
        dist[src] = 0;
        for(int i = 0; i < v; i++){
            for(auto e : edge){
                int u = e[0], v_ = e[1], w = e[2];
                if(dist[u] != 1e8 && dist[u] + w < dist[v_]){
                    if(i == v - 1) return {-1};
                    dist[v_] = dist[u] + w;
                }
            }
        }
        return dist;
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        vector<vector<int>> edge;
        int n, m;
        cin >> n >> m;
        for(int i = 0; i < m; i++){
            int u, v, w;
            cin >> u >> v >> w;
            edge.push_back(vector<int>{u, v, w});
        }
        int src = 1;
        vector<int> ans = bellman_ford(n, edge, src);
        cout << ans[n] << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.