Browse curriculum

Reorder Routes to Make All Paths Lead to the City Zero

Reorder Routes to Make All Paths Lead to the City Zero: the one-way roads between n cities form a tree. Count the fewest roads to reverse so every city can reach city 0: DFS from 0 and count the roads that point away from it.

Problem Understanding

Reorder Routes to Make All Paths Lead to the City Zero (LeetCode 1466): there are n cities and n − 1 one-way roads, connections[i] = [a, b] for a road from a to b, and ignoring direction they connect every city (a tree). Return the minimum number of roads to reverse so that every city can reach city 0.

Examples: n = 6, [[0,1],[1,3],[2,3],[4,0],[4,5]] → 3; n = 5, [[1,0],[1,2],[3,2],[3,4]] → 2; n = 3, [[1,0],[2,0]] → 0.

The Intuition: Walk Away From 0, Count Roads Going Your Way

Picture the tree hanging from city 0. Every road should point up, toward 0. A search that starts at 0 always moves down, away from 0, so any road it walks in the road’s own direction is pointing down and must be flipped.

  1. Store each road twice: a → b goes into a’s list as (b, 1) and into b’s list as (a, 0). The 1 means "walking this follows the road".
  2. DFS from city 0, ignoring direction, visiting each city once.
  3. Add the mark of every road you walk. Roads marked 1 point away from 0 and need reversing.

It is a plain graph DFS, like Keys and Rooms, with one bit of extra information on each edge. Number of Provinces uses the same search on an undirected graph.

Reorder Routes to Make All Paths Lead to the City Zero Visualization

CITY 0 ON THE LEFT · GREEN = ALREADY LEADS TO 0 · RED = REVERSED

BUILD BOTH-WAY LISTS

city

:

reversed

0

Answer

:

stack (top last)

0

 

Store every road in both cities' lists: 1 where it leaves the city, 0 where it arrives. Start at city 0

Next

Pop city 0: walk each road to a city not seen yet, away from 0

Free preview: the first 4 of 13 steps

roads

n

6

City 0 is on the left and each column to the right is one road further from it, so a road that leads to 0 points left. As the DFS walks a road it turns green if it already points to 0, or is redrawn pointing left in red if it has to be reversed. Try All away, where every road is reversed, and Example 3, where none is.

Reorder Routes to Make All Paths Lead to the City Zero Dry Run

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]].

Pop city Road walked Direction Reversed so far
0 0 → 1 away from 0: reverse 1
0 4 → 0 toward 0: keep 1
4 4 → 5 away from 0: reverse 2
5 (none new) 2
1 1 → 3 away from 0: reverse 3
3 2 → 3 toward 0: keep 3
2 (none new) 3

Answer: 3.

Reorder Routes to Make All Paths Lead to the City Zero LeetCode Solution

Adjacency lists with a direction mark on each entry, then an iterative DFS from city 0. The C version keeps its lists in arrays.

Reorder Routes to Make All Paths Lead to the City Zero Code
1var minReorder = function(n, connections) {
2 const graph = Array.from({ length: n }, () => []);
3 for (const [a, b] of connections) {
4 graph[a].push([b, 1]);
5 graph[b].push([a, 0]);
6 }
7 const seen = new Array(n).fill(false);
8 seen[0] = true;
9 const stack = [0];
10 let changes = 0;
11 while (stack.length > 0) {
12 const city = stack.pop();
13 for (const [next, away] of graph[city]) {
14 if (!seen[next]) {
15 seen[next] = true;
16 changes += away;
17 stack.push(next);
18 }
19 }
20 }
21 return changes;
22};

Reorder Routes to Make All Paths Lead to the City Zero in Python, Java, C++, TypeScript and C

Reorder Routes to Make All Paths Lead to the City Zero in Python
class Solution:
    def minReorder(self, n: int, connections: List[List[int]]) -> int:
        graph = [[] for _ in range(n)]
        for a, b in connections:
            graph[a].append((b, 1))
            graph[b].append((a, 0))
        seen = [False] * n
        seen[0] = True
        stack = [0]
        changes = 0
        while stack:
            city = stack.pop()
            for nxt, away in graph[city]:
                if not seen[nxt]:
                    seen[nxt] = True
                    changes += away
                    stack.append(nxt)
        return changes
Reorder Routes to Make All Paths Lead to the City Zero in Java
class Solution {
    public int minReorder(int n, int[][] connections) {
        List<List<int[]>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int[] c : connections) {
            graph.get(c[0]).add(new int[]{c[1], 1});
            graph.get(c[1]).add(new int[]{c[0], 0});
        }
        boolean[] seen = new boolean[n];
        seen[0] = true;
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(0);
        int changes = 0;
        while (!stack.isEmpty()) {
            int city = stack.pop();
            for (int[] edge : graph.get(city)) {
                if (!seen[edge[0]]) {
                    seen[edge[0]] = true;
                    changes += edge[1];
                    stack.push(edge[0]);
                }
            }
        }
        return changes;
    }
}
Reorder Routes to Make All Paths Lead to the City Zero in C++
class Solution {
public:
    int minReorder(int n, vector<vector<int>>& connections) {
        vector<vector<pair<int, int>>> graph(n);
        for (auto& c : connections) {
            graph[c[0]].push_back({c[1], 1});
            graph[c[1]].push_back({c[0], 0});
        }
        vector<bool> seen(n, false);
        seen[0] = true;
        vector<int> stack = {0};
        int changes = 0;
        while (!stack.empty()) {
            int city = stack.back();
            stack.pop_back();
            for (auto [next, away] : graph[city]) {
                if (!seen[next]) {
                    seen[next] = true;
                    changes += away;
                    stack.push_back(next);
                }
            }
        }
        return changes;
    }
};
Reorder Routes to Make All Paths Lead to the City Zero in TypeScript
function minReorder(n: number, connections: number[][]): number {
    const graph: [number, number][][] = Array.from({ length: n }, () => []);
    for (const [a, b] of connections) {
        graph[a].push([b, 1]);
        graph[b].push([a, 0]);
    }
    const seen: boolean[] = new Array(n).fill(false);
    seen[0] = true;
    const stack: number[] = [0];
    let changes = 0;
    while (stack.length > 0) {
        const city = stack.pop()!;
        for (const [next, away] of graph[city]) {
            if (!seen[next]) {
                seen[next] = true;
                changes += away;
                stack.push(next);
            }
        }
    }
    return changes;
}
Reorder Routes to Make All Paths Lead to the City Zero in C
static int *head, *nxt, *to, *away, edges;

static void addRoad(int from, int target, int mark) {
    to[edges] = target;
    away[edges] = mark;
    nxt[edges] = head[from];
    head[from] = edges++;
}

int minReorder(int n, int** connections, int connectionsSize, int* connectionsColSize) {
    head = malloc(n * sizeof(int));
    nxt = malloc(2 * connectionsSize * sizeof(int));
    to = malloc(2 * connectionsSize * sizeof(int));
    away = malloc(2 * connectionsSize * sizeof(int));
    edges = 0;
    for (int i = 0; i < n; i++) {
        head[i] = -1;
    }
    for (int i = 0; i < connectionsSize; i++) {
        addRoad(connections[i][0], connections[i][1], 1);
        addRoad(connections[i][1], connections[i][0], 0);
    }
    bool* seen = calloc(n, sizeof(bool));
    int* stack = malloc(n * sizeof(int));
    int top = 0, changes = 0;
    seen[0] = true;
    stack[top++] = 0;
    while (top > 0) {
        int city = stack[--top];
        for (int e = head[city]; e != -1; e = nxt[e]) {
            if (!seen[to[e]]) {
                seen[to[e]] = true;
                changes += away[e];
                stack[top++] = to[e];
            }
        }
    }
    free(head);
    free(nxt);
    free(to);
    free(away);
    free(seen);
    free(stack);
    return changes;
}

Edge Cases & Common Mistakes

  • Searching only along road directions: roads pointing into 0 are never crossed from 0, so most of the tree is missed.
  • Counting the wrong roads: count roads walked in their own direction (away from 0), not against it.
  • Recursion depth: with up to 50,000 cities a chain makes a recursive DFS 50,000 calls deep; the stack-based version avoids that.
  • Every road already correct: the answer is 0, as in a star with all roads pointing at 0.

Summary

Store each road in both directions with a mark for its real direction, DFS from city 0, and add up the marks of the roads walked in their own direction. O(n) time and space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Build the lists

    For each road a → b, add (b, 1) to a’s list and (a, 0) to b’s list.

  2. Search from 0

    DFS from city 0, visiting each unvisited neighbour once.

  3. Count

    Add the stored mark of every road walked; the total is the number of roads to reverse.

Frequently asked questions

Why does every road that points away from 0 need reversing?

The roads form a tree, so each city has exactly one path to city 0, and every road on it must point toward 0. A DFS from 0 walks each road from the city nearer 0 to the one further away. If the road points the same way the DFS walks it, it leads away from 0 and has to be reversed; if it points the other way it is already right.


Why store each road in both cities’ lists?

Searching from 0 has to cross roads against their direction, because roads that already lead to 0 point at it. Storing a → b in both lists lets the DFS walk every road, and the 1 or 0 stored with it records whether walking it from that side follows the road (so it must be reversed) or goes against it.


Is the answer always the minimum?

Yes. Each road is on the only path from one city to 0, so a road pointing away must be reversed whatever else changes, and a road already pointing to 0 never needs to be. The count is forced, so there is nothing to optimise beyond counting.


Can BFS replace the DFS?

Yes. Any search from 0 that crosses every road once gives the same count, because the count depends only on each road’s direction relative to 0. BFS with a queue and DFS with a stack or recursion are all O(n).

New to the technique behind this problem? Watch it run step by step:

Topological Sort Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description