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
| class Solution { List<int[]>[] g;
public int minReorder(int n, int[][] connections) { g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (int[] c : connections) { int a = c[0], b = c[1]; g[a].add(new int[]{b, 1}); g[b].add(new int[]{a, 0}); } return dfs(0, -1); }
private int dfs(int x, int pa) { int ans = 0; for (int[] e : g[x]) { int y = e[0], c = e[1]; if (y != pa) { ans += c + dfs(y, x); } } return ans; } }
|