Taro Logo

Reorder Routes to Make All Paths Lead to the City Zero

Medium
3 views
2 months ago

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] = [a[i], b[i]] represents a road from city a[i] to city b[i].

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.

Example 1:

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).

Example 2:

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

Example 3:

n = 3, connections = [[1,0],[2,0]] Output: 0

Constraints:

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 <= a[i], b[i] <= n - 1
  • a[i] != b[i]
Sample Answer

Data Structures and Algorithms: Minimum Reorientations to Reach City 0

This problem asks us to find the minimum number of road reorientations needed in a tree-like network of cities so that every city can reach city 0 (the capital). Let's explore different approaches to solve this.

1. Naive Approach: Brute-Force (Not Efficient)

A very basic approach would be to try all possible orientations of the roads and, for each orientation, check if every city can reach city 0. This would involve generating all possible direction combinations, which is highly inefficient, especially for larger networks. We can discard this.

2. Optimal Approach: Depth-First Search (DFS)

A more efficient approach utilizes Depth-First Search (DFS) to traverse the graph. We start from city 0 and explore the graph. While traversing, we count the number of roads that need to be reoriented to reach city 0.

Algorithm:

  1. Build Adjacency List: Create an adjacency list to represent the graph. For each connection [a, b], add b to the list of neighbors of a, and also add a to the list of neighbors of b. We can store the original direction as a part of the adjancency list.
  2. DFS Traversal: Start a DFS traversal from city 0.
  3. Count Reorientations: During the DFS, if we traverse an edge from a to b and the original connection was [a, b], then it is correctly oriented, and we don't need to reorient it. However, if the original connection was [b, a], then we need to reorient it, so we increment our counter.
  4. Return Count: After the DFS traversal, return the counter, which represents the minimum number of reorientations needed.

Code (Python):

def min_reorientations(n: int, connections: list[list[int]]) -> int:
    adj = [[] for _ in range(n)]
    for a, b in connections:
        adj[a].append((b, 0))  # 0 indicates original direction: a -> b
        adj[b].append((a, 1))  # 1 indicates original direction: b -> a

    visited = [False] * n
    reorientations = 0

    def dfs(node):
        nonlocal reorientations
        visited[node] = True
        for neighbor, direction in adj[node]:
            if not visited[neighbor]:
                if direction == 1:
                    reorientations += 1
                dfs(neighbor)

    dfs(0)
    return reorientations

# Example Usage:
n = 6
connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
result = min_reorientations(n, connections)
print(f"Minimum reorientations: {result}")  # Output: 3

n = 5
connections = [[1,0],[1,2],[3,2],[3,4]]
result = min_reorientations(n, connections)
print(f"Minimum reorientations: {result}")  # Output: 2

n = 3
connections = [[1,0],[2,0]]
result = min_reorientations(n, connections)
print(f"Minimum reorientations: {result}")  # Output: 0

3. Big(O) Runtime Analysis

  • Time Complexity: O(N), where N is the number of cities. This is because the DFS traversal visits each city and each road once.

4. Big(O) Space Usage Analysis

  • Space Complexity: O(N), where N is the number of cities. This is due to the adjacency list which, in the worst case (a complete graph), can store information about all possible connections between cities. The visited array also contributes O(N) space.

5. Edge Cases

  • Empty Graph: If n is 0 or 1, or if connections is empty, return 0 (no reorientations needed).
  • Disconnected Graph: The problem statement guarantees that the graph is connected, so we don't need to explicitly handle disconnected graphs. However, if the graph were disconnected, the algorithm would only explore the component connected to city 0, and only reorientations within that component would be counted. Cities in other components would not be able to reach city 0, but the problem assumes a connected graph.
  • Cycles: The problem states that the network forms a tree, so there are no cycles. If there were cycles, the DFS algorithm would still work correctly because the visited array prevents infinite loops. The reorientation count might be different depending on the arbitrary order in which the DFS explores the cycle, but the algorithm will still terminate and give a valid answer if the capital can be reached from every node.