Print Shortest Path
Pattern: Shortest paths
Run Dijkstra from vertex 1 and remember, for each vertex, which vertex its best distance came from. At the end walk these parents back from n to 1 and reverse the list. If n is unreachable, return [-1].
The problem
Given an undirected weighted graph with vertices 1 to n, return a shortest path from 1 to n as a list of vertices, or
[-1] if n cannot be reached. Edges are [u, v, weight]. The tests only use graphs with a single shortest path. GFG's
version also puts the path's weight first; this guide returns only the path.
Think first
- What does Dijkstra already know when it improves a distance?
- How do you rebuild the path?
- Why reverse it?
Hints
Brute force, and why it fails
Run Dijkstra, then search for a path whose edges match the distances: more work for the same result.
The key insight
Recording a parent at each improvement keeps exactly the tree of shortest paths, so the path is one walk back.
Dry run
Vertices 1..5; edges 1-2 (2), 2-5 (5), 2-3 (4), 1-4 (1), 4-3 (3), 3-5 (1). Dijkstra from 1.
The plan
Dijkstra; on improving v through u: parent[v] = u
path = walk parent from n to 1; reverse
Complexity
- Time
O(E log V)- Space
O(V + E)
Dijkstra plus a walk of at most V steps.
Edge cases
- n unreachable: [-1].
- n = 1: [1].
- A direct edge that is longer than a detour.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> shortestPathPrint(int n, int[][] edges) { // vertices 1..n, from 1 to n
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(new int[]{e[1], e[2]}); adj.get(e[1]).add(new int[]{e[0], e[2]}); }
long[] dist = new long[n + 1];
int[] parent = new int[n + 1]; // the vertex we came from on the best path
Arrays.fill(dist, Long.MAX_VALUE);
dist[1] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
pq.add(new long[]{0, 1});
while (!pq.isEmpty()) {
long[] top = pq.poll();
int u = (int) top[1];
if (top[0] > dist[u]) continue;
for (int[] e : adj.get(u)) {
if (dist[u] + e[1] < dist[e[0]]) {
dist[e[0]] = dist[u] + e[1];
parent[e[0]] = u; // remember how we got here
pq.add(new long[]{dist[e[0]], e[0]});
}
}
}
if (dist[n] == Long.MAX_VALUE) return Arrays.asList(-1);
LinkedList<Integer> path = new LinkedList<>();
for (int v = n; v != 1; v = parent[v]) path.addFirst(v); // walk the parents back from n
path.addFirst(1);
return path;
}
}C++
class Solution {
public:
vector<int> shortestPathPrint(int n, vector<vector<int>>& edges) { // vertices 1..n, from 1 to n
vector<vector<pair<int, int>>> adj(n + 1);
for (const vector<int>& e : edges) { adj[e[0]].push_back(make_pair(e[1], e[2])); adj[e[1]].push_back(make_pair(e[0], e[2])); }
vector<long long> dist(n + 1, LLONG_MAX);
vector<int> parent(n + 1, 0); // the vertex we came from on the best path
dist[1] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
pq.push(make_pair(0LL, 1));
while (!pq.empty()) {
pair<long long, int> top = pq.top();
pq.pop();
int u = top.second;
if (top.first > dist[u]) continue;
for (const pair<int, int>& e : adj[u]) {
if (dist[u] + e.second < dist[e.first]) {
dist[e.first] = dist[u] + e.second;
parent[e.first] = u; // remember how we got here
pq.push(make_pair(dist[e.first], e.first));
}
}
}
if (dist[n] == LLONG_MAX) return vector<int>{-1};
vector<int> path;
for (int v = n; v != 1; v = parent[v]) path.push_back(v); // walk the parents back from n
path.push_back(1);
reverse(path.begin(), path.end());
return path;
}
};Python
import heapq
class Solution:
def shortestPathPrint(self, n: int, edges: list[list[int]]) -> list[int]: # vertices 1..n, from 1 to n
adj = [[] for _ in range(n + 1)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
dist, parent = [float("inf")] * (n + 1), [0] * (n + 1) # parent: where the best path came from
dist[1] = 0
pq = [(0, 1)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v], parent[v] = d + w, u # remember how we got here
heapq.heappush(pq, (dist[v], v))
if dist[n] == float("inf"):
return [-1]
path = [n]
while path[-1] != 1:
path.append(parent[path[-1]]) # walk the parents back from n
return path[::-1]Common mistakes
- Recording the parent on every relaxation attempt, not just improvements.
- Forgetting to reverse.