source: https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/description/
Reorder Routes to Make All Paths Lead to the City Zero
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] = [ai, bi] represents a road from city ai to city bi.
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:
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).
Example 2:
Input: 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:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
- 2 <= n <= 5 * 104
- connections.length == n – 1
- connections[i].length == 2
- 0 <= ai, bi <= n – 1
- ai != bi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class Solution { public int minReorder(int n, int[][] connections) { Map<Integer, List<Pair>> map = new HashMap<>(); //create a graph for(int[] connection: connections){ map.computeIfAbsent(connection[0], k->new ArrayList<>()).add(new Pair(connection[1], 1)); map.computeIfAbsent(connection[1], k->new ArrayList<>()).add(new Pair(connection[0], 0)); } //idea is to start from node 0, perform dfs traversal to reach each and every node //either by original connection or artificial connection //if you are able to reach a node from node 0, then connection needs to be flipped dfs(map, 0, -1, new HashSet<>()); return count; } int count = 0; private void dfs(Map<Integer, List<Pair>> map, int node, int parent, HashSet<Integer> seen){ if(!seen.contains(node)){ for(Pair p: map.get(node)){ if(p.val != parent){ count = count + p.sign; dfs(map, p.val, node, seen); } } seen.add(node); } } static class Pair { int val; //1 denites original connection //0 denites artiifical connection, not existed in the original connections int sign; public Pair (int val, int sign){ this.val = val; this.sign = sign; } } } |
Time Complexity
O(n + m) where n is the number of nodes in your tree, and m is the number of edges.
Space Complexity
O(n + m) + O(n): adjacency list representation of a graph + to store the visited nodes