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
| class Solution { private static class Edge { private final int from; private final int to; private final int direction;
public Edge(int from, int to, int direction) { this.from = from; this.to = to; this.direction = direction; } }
public int minReorder(int n, int[][] connections) { List<List<Edge>> nodeToEdgeListMap = new ArrayList<>(); for (int i = 0; i < n; i++) { nodeToEdgeListMap.add(new ArrayList<>()); } for (int[] connection : connections) { int nodeA = connection[0], nodeB = connection[1]; nodeToEdgeListMap.get(nodeA).add(new Edge(nodeA, nodeB, 1)); nodeToEdgeListMap.get(nodeB).add(new Edge(nodeB, nodeA, 0)); }
return dfs(0, -1, nodeToEdgeListMap); }
private int dfs(int from, int parent, List<List<Edge>> nodeToEdgeListMap) { int res = 0;
for (Edge edge : nodeToEdgeListMap.get(from)) { if (edge.to == parent) { continue; }
res += edge.direction + dfs(edge.to, from, nodeToEdgeListMap); }
return res; } }
|