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 49 50 51 52 53 54 55 56 57
| class Solution { public int[] maxTargetNodes(int[][] edges1, int[][] edges2) { int n = edges1.length + 1; int m = edges2.length + 1; boolean[] color1 = new boolean[n]; boolean[] color2 = new boolean[m]; int[] nums = divide(edges1, color1); int[] nums2 = divide(edges2, color2);
int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = nums[((color1[i])? 0 :1)] + Math.max(nums2[0], nums2[1]); } return result; }
int[] divide(int[][] edges, boolean[] color) { List<List<Integer>> connections = new ArrayList<>(); int n = edges.length + 1; for (int x = 0; x < n; x++) { connections.add(new ArrayList<>()); } for (int[] edge : edges) { connections.get(edge[0]).add(edge[1]); connections.get(edge[1]).add(edge[0]); } int ans = dfs(0, -1 , 0, connections, color); return new int[] {ans, n - ans}; }
int dfs (int n, int p, int depth, List<List<Integer>> connections, boolean[] colors) { List<Integer> list = connections.get(n); int ans = (depth %2==0) ? 1 : 0; colors[n] = (depth %2 == 0); for (int c : list) { if (c == p) { continue; } ans += dfs(c, n, depth + 1, connections, colors); } return ans; } }
|