#1466

Reorder Routes to Make All Paths Lead to the City Zero

Medium
Depth-First SearchBreadth-First SearchGraph TheoryGraph TraversalDepth-First SearchTree Structures
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses Depth-First Search (DFS) to traverse the graph while counting the number of roads that need to be reversed. This method is efficient because it explores each road only once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph representation of the cities and roads, marking each road with a flag indicating if it needs to be reversed.
  2. 2Step 2: Perform a DFS starting from city 0, counting the roads that need to be reversed as you traverse.
  3. 3Step 3: Return the total count of roads that need to be reversed.
solution.py22 lines
1# Full working Python code
2from collections import defaultdict
3
4def minReorder(n, connections):
5    graph = defaultdict(list)
6    for a, b in connections:
7        graph[a].append((b, 1))  # 1 indicates a road that needs to be reversed
8        graph[b].append((a, 0))  # 0 indicates a road that is fine
9
10    count = 0
11    visited = set()
12
13    def dfs(city):
14        nonlocal count
15        visited.add(city)
16        for neighbor, needs_reverse in graph[city]:
17            if neighbor not in visited:
18                count += needs_reverse
19                dfs(neighbor)
20
21    dfs(0)
22    return count

Complexity note: The complexity is linear because we visit each city and road exactly once during the DFS traversal.

  • 1Understanding the direction of roads is crucial.
  • 2Graph traversal techniques like DFS are effective for tree structures.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.