Graph Theory37 sections · 1633 units
Open in Course

CSES 1667 Message Route - Path Reconstruction Algorithm

Backtracking

Run BFS and record parents as you go:

// During BFS, when visiting v from u:
parent[v] = u

// After BFS, reconstruct path from s to t:
path = []
current = t
while current != 0:
    path.append(current)
    current = parent[current]
path.reverse()

When you process node uu and visit neighbor vv, set parent[v] = u before adding vv to the queue. After BFS completes, start at tt and backtrack through parents until you reach ss. Reverse to get the path from ss to tt.

If you never reached tt during BFS, parent[t] is still 00, meaning no path exists.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.