MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / shortestPath

Function shortestPath

cpp/Graphs/shortest_path.cpp:5–49  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3#include <limits>
4
5std::vector<int> shortestPath(int n, std::vector<std::vector<int>>& edges, int start) {
6 std::vector<std::vector<std::pair<int, int>>> graph(n);
7 std::vector<int> distances(n, std::numeric_limits<int>::max());
8 distances[start] = 0;
9 // Represent the graph as an adjacency list.
10 for (auto& edge : edges) {
11 int u = edge[0], v = edge[1], w = edge[2];
12 graph[u].push_back({v, w});
13 graph[v].push_back({u, w});
14 }
15 using P = std::pair<int, int>;
16 std::priority_queue<P, std::vector<P>, std::greater<P>> minHeap;
17 minHeap.push({0, start});
18 // Use Dijkstra's algorithm to find the shortest path between the start node
19 // and all other nodes.
20 while (!minHeap.empty()) {
21 int currDist = minHeap.top().first;
22 int currNode = minHeap.top().second;
23 minHeap.pop();
24 // If the current distance to this node is greater than the recorded
25 // distance, we've already found the shortest distance to this node.
26 if (currDist > distances[currNode]) {
27 continue;
28 }
29 // Update the distances of the neighboring nodes.
30 for (auto& neighborPair : graph[currNode]) {
31 int neighbor = neighborPair.first;
32 int weight = neighborPair.second;
33 int neighborDist = currDist + weight;
34 // Only update the distance if we find a shorter path to this
35 // neighbor.
36 if (neighborDist < distances[neighbor]) {
37 distances[neighbor] = neighborDist;
38 minHeap.push({neighborDist, neighbor});
39 }
40 }
41 }
42 // Convert all infinity values to -1, representing unreachable nodes.
43 for (int i = 0; i < n; i++) {
44 if (distances[i] == std::numeric_limits<int>::max()) {
45 distances[i] = -1;
46 }
47 }
48 return distances;
49}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected