Directory link:
Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog
GitHub synchronous question brushing project:
https://github.com/September26/java-algorithms
Original title link:LeetCode official website - the technology growth platform loved by geeks around the world
describe:
n
cities, numbered from 0
to n-1
, with a total of n-1
routes. Therefore, there is only one route available to travel between two different cities (the network of routes forms a tree). Last year, the Ministry of Transport decided to reroute the route to change traffic congestion.
The route is represented by connections
, where connections[i] = [a, b]
means from the city a
to b
a directed route.
This year, city 0 will host a big competition and many tourists want to go to city 0.
Could you please help re-route so that city 0 is accessible from every city. Returns the minimum number of routes that require a change of direction.
Question data Guarantee Each city can reach city 0 after re-planning the route direction.
Example 1:
Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4, 5]] Output: 3 Explanation: Change the direction of the route shown in red so that every city can reach city 0 .
Example 2:
Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 Explanation: Change the direction of the route shown in red so that every city can reach city 0 .
Example 3:
Import:n = 3, connections = [[1,0],[2,0]] Exit: 0
hint:
2 <= n <= 5 * 10^4
connections.length == n-1
connections[i].length == 2
0 <= connections[i][0], connections[i][1] <= n-1
connections[i][0] != connections[i][1]
Problem-solving ideas:
The breadth-first search method is used here. Starting from 0, first find all the nodes that can be reached in one step. If there are reverse ones, the number is +1. If it is positive, no processing is required.
Then find all the nodes that can be reached in 2 steps and go down in sequence.
Code:
class Solution {
Map<Integer, List<Integer>> toMap = new HashMap<>();
Map<Integer, List<Integer>> fromMap = new HashMap<>();
boolean[] dp;
public int minReorder(int n, int[][] connections) {
dp = new boolean[n];
for (int[] connection : connections) {
int from = connection[0];
int to = connection[1];
List<Integer> integers1 = toMap.computeIfAbsent(to, k -> new ArrayList<>());
integers1.add(from);
List<Integer> integers2 = fromMap.computeIfAbsent(from, k -> new ArrayList<>());
integers2.add(to);
}
int sum = 0;
List<Integer> list = new ArrayList<>();
list.add(0);
dp[0] = true;
while (list.size() > 0) {
List<Integer> newList = new ArrayList<>();
for (int i : list) {
List<Integer> integers = toMap.get(i);
List<Integer> integers1 = fromMap.get(i);
if (integers != null) {
for (int key : integers) {
if (dp[key]) {
continue;
}
dp[key] = true;
newList.add(key);
}
}
if (integers1 != null) {
for (int key : integers1) {
if (dp[key]) {
continue;
}
dp[key] = true;
sum++;
newList.add(key);
}
}
}
list = newList;
}
return sum;
}
}