#1466
Medium Algorithms Reorder routes to make all paths lead to the city zero
Depth-First Search Breadth-First Search Graph Theory
65.6% acceptance
Feb 25, 2026
4624
149
There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree).
Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0 after reorder.
Solution
Rust
Time O(n * m)
Space O(n * m)
use std::collections::VecDeque;
impl Solution {
pub fn min_reorder(n: i32, connections: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
// adj[u] = list of (v, cost): cost=1 if original edge u->v, cost=0 if reverse
let mut adj = vec![vec![]; n];
for c in &connections {
let (a, b) = (c[0] as usize, c[1] as usize);
adj[a].push((b, 1)); // original: a->b, need to reverse to go toward 0
adj[b].push((a, 0)); // reverse: b->a, already points toward 0
}
let mut visited = vec![false; n];
let mut queue = VecDeque::new();
queue.push_back(0usize);
visited[0] = true;
let mut count = 0;
while let Some(u) = queue.pop_front() {
for &(v, cost) in &adj[u] {
if !visited[v] {
visited[v] = true;
count += cost;
queue.push_back(v);
}
}
}
count
}
}