DSA Graphs

Reorder Routes to Make All Paths Lead to the City Zero

BFS/DFS the undirected tree from city 0; count edges that point away — those must be flipped.

Medium
Time O(V + E) Space O(V + E)
LeetCode
4 min read
graph bfs tree

Problem#

A tree of n cities connected by n - 1 directed roads. Reorient the minimum number of roads so every city can reach city 0. Return that minimum.

Examples#

  • n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]3
  • n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]2

Constraints#

  • 2 <= n <= 5 * 10^4. The underlying graph is a tree.

Approach#

Build the graph with each edge stored bidirectionally, but tag the direction. BFS/DFS from city 0; whenever we traverse an edge in its original direction (away from 0), it must be reversed — increment the answer.

Solution#

Reorder Routes to Make All Paths Lead to the City Zero
class Solution {
public:
int minReorder(int n, vector<vector<int>>& connections) {
vector<vector<pair<int,int>>> adj(n);
for (auto& c : connections) {
adj[c[0]].push_back({c[1], 1}); // original direction
adj[c[1]].push_back({c[0], 0}); // reverse
}
vector<bool> seen(n, false);
seen[0] = true;
queue<int> q;
q.push(0);
int flips = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
for (auto [v, isOriginal] : adj[u]) {
if (seen[v]) continue;
seen[v] = true;
flips += isOriginal;
q.push(v);
}
}
return flips;
}
};

Editorial#

In a tree, the path between any node and city 0 is unique. We walk outward from 0; every directed edge encountered with its arrow pointing away must be reversed. The tag bit on edges encodes that direction.

Complexity#

  • Time: O(V + E).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.