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

MediumDepth-First SearchBreadth-First SearchGraph
Problem
#1466
Reading time
2 min

The problem

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.

Example

Input
n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output
3
Explanation
Change the direction of edges show in red such that each node can reach the node 0 (capital).

Python solution

Python
class Solution:
    def minReorder(self, n: int, connections: List[List[int]]) -> int:
        def dfs(a: int, fa: int) -> int:
            return sum(c + dfs(b, a) for b, c in g[a] if b != fa)

        g = [[] for _ in range(n)]
        for a, b in connections:
            g[a].append((b, 1))
            g[b].append((a, 0))
        return dfs(0, -1)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Breadth-First Search

Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.

The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero?
LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero is rated Medium on LeetCode.
What is the time complexity of LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero cover?
LeetCode 1466. Reorder Routes to Make All Paths Lead to the City Zero is tagged Depth-First Search, Breadth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview