-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderRoutes.java
More file actions
48 lines (35 loc) · 1.59 KB
/
Copy pathReorderRoutes.java
File metadata and controls
48 lines (35 loc) · 1.59 KB
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
40
41
42
43
44
45
46
47
48
package LeetcodePractice;
import java.util.*;
public class ReorderRoutes {
public int minReorder(int n, int[][] connections) {
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] conn : connections) {
int u = conn[0], v = conn[1];
graph.computeIfAbsent(u, k -> new ArrayList<>()).add(new int[]{v, 1}); // original direction
graph.computeIfAbsent(v, k -> new ArrayList<>()).add(new int[]{u, 0}); // reverse direction
}
boolean[] visited = new boolean[n];
return dfs(0, graph, visited);
}
private int dfs(int node, Map<Integer, List<int[]>> graph, boolean[] visited) {
visited[node] = true;
int changes = 0;
for (int[] neighbor : graph.getOrDefault(node, new ArrayList<>())) {
int nextNode = neighbor[0];
int needsChange = neighbor[1];
if (!visited[nextNode]) {
changes += needsChange + dfs(nextNode, graph, visited);
}
}
return changes;
}
public static void main(String[] args) {
ReorderRoutes solution = new ReorderRoutes();
int[][] connections1 = {{0,1},{1,3},{2,3},{4,0},{4,5}};
System.out.println("Output: " + solution.minReorder(6, connections1)); // Output: 3
int[][] connections2 = {{1,0},{1,2},{3,2},{3,4}};
System.out.println("Output: " + solution.minReorder(5, connections2)); // Output: 2
int[][] connections3 = {{1,0},{2,0}};
System.out.println("Output: " + solution.minReorder(3, connections3)); // Output: 0
}
}