Leetcode 1466: Reorder Routes to Make All Paths Lead to the City Zero

grid47
grid47
Exploring patterns and algorithms
Jun 13, 2024 7 min read

You are given n cities and n - 1 roads, forming a tree structure. The roads have been directed, and some roads may need to be reoriented to ensure all cities can reach the capital city (city 0). Your task is to determine the minimum number of road reorientations required to make it possible for each city to reach city 0.
Problem
Approach
Steps
Complexity
Input: The input consists of two parameters: the number of cities, n, and a list of connections, where each connection represents a directed road between two cities.
Example: Input: n = 6, connections = [[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]]
Constraints:
• 2 <= n <= 5 * 10^4
• connections.length == n - 1
• connections[i].length == 2
• 0 <= ai, bi <= n - 1
• ai != bi
Output: The output is a single integer representing the minimum number of roads that need to be reoriented to ensure all cities can reach city 0.
Example: Output: 3
Constraints:
• The minimum number of roads that need to be reoriented.
Goal: To find the minimum number of road reorientations required for all cities to reach the capital city.
Steps:
• Construct a graph representing the cities and roads.
• For each road, if it is directed away from the capital, count it as a reorientation.
• Perform a breadth-first search (BFS) starting from the capital city, visiting each city and checking if a road needs to be reoriented to allow travel to city 0.
• Return the total number of reorientations.
Goal: The problem guarantees that each city can reach city 0 after reordering the roads.
Steps:
• The number of cities is between 2 and 5 * 10^4.
• Each city is connected by exactly one road to another city, forming a tree structure.
Assumptions:
• The input guarantees that each city can eventually reach city 0 after reordering the roads.
• All roads are directed, and the tree structure is guaranteed.
Input: Input: n = 6, connections = [[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]]
Explanation: Output: 3. To ensure that every city can reach city 0, we need to reorient three roads: from city 1 to city 0, from city 3 to city 1, and from city 4 to city 0.

Input: Input: n = 5, connections = [[1, 0], [1, 2], [3, 2], [3, 4]]
Explanation: Output: 2. We need to reorient the road from city 1 to city 0 and from city 2 to city 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus