1466. Reorder Routes to Make All Paths Lead to the City Zero
Problem
Cities 0…n − 1 are joined by n − 1 one-way roads that would form a tree if undirected; connections[i] = [a, b] is a road from a to b. Return the minimum number of roads to reverse so every city can reach city 0.
Example: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] → 3
Constraints: n ≤ 5·10⁴.
Treat roads as undirected but remember direction: an original edge a → b costs 1 when traversed away from 0 (it must be reversed), its reverse costs 0. DFS from 0 summing costs.
Complexity: O(n).
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
g = defaultdict(list)
for a, b in connections:
g[a].append((b, 1)) # original direction, points away from 0 -> needs flip
g[b].append((a, 0))
seen, st, flips = {0}, [0], 0
while st:
u = st.pop()
for v, cost in g[u]:
if v not in seen:
seen.add(v)
flips += cost
st.append(v)
return flips
assert Solution().minReorder(6, [[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]]) == 3
assert Solution().minReorder(5, [[1, 0], [1, 2], [3, 2], [3, 4]]) == 2
class Solution {
public int minReorder(int n, int[][] connections) {
List<List<int[]>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
for (int[] c : connections) { g.get(c[0]).add(new int[]{c[1], 1}); g.get(c[1]).add(new int[]{c[0], 0}); }
boolean[] seen = new boolean[n];
seen[0] = true;
Deque<Integer> st = new ArrayDeque<>(List.of(0));
int flips = 0;
while (!st.isEmpty())
for (int[] e : g.get(st.pop()))
if (!seen[e[0]]) { seen[e[0]] = true; flips += e[1]; st.push(e[0]); }
return flips;
}
}
func minReorder(n int, connections [][]int) int {
g := make([][][2]int, n) // (neighbor, 1 if the road points away from city 0's side)
for _, c := range connections {
g[c[0]] = append(g[c[0]], [2]int{c[1], 1})
g[c[1]] = append(g[c[1]], [2]int{c[0], 0})
}
seen, st, flips := make([]bool, n), []int{0}, 0
seen[0] = true
for len(st) > 0 {
u := st[len(st)-1]
st = st[:len(st)-1]
for _, e := range g[u] {
if !seen[e[0]] {
seen[e[0]] = true
flips += e[1]
st = append(st, e[0])
}
}
}
return flips
}