1+ import java .util .*;
2+
3+ class Solution {
4+ public int [] maxTargetNodes (int [][] edges1 , int [][] edges2 ) {
5+ int n = edges1 .length + 1 ;
6+ int m = edges2 .length + 1 ;
7+
8+ List <List <Integer >> tree1 = buildGraph (edges1 , n );
9+ List <List <Integer >> tree2 = buildGraph (edges2 , m );
10+
11+ int [] color1 = new int [2 ];
12+ int [] nodeColor1 = new int [n ];
13+ bfs (tree1 , color1 , nodeColor1 );
14+
15+ int [] color2 = new int [2 ];
16+ int [] nodeColor2 = new int [m ];
17+ bfs (tree2 , color2 , nodeColor2 );
18+
19+ int maxColor2 = Math .max (color2 [0 ], color2 [1 ]);
20+
21+ int [] result = new int [n ];
22+ for (int i = 0 ; i < n ; i ++) {
23+ result [i ] = color1 [nodeColor1 [i ]] + maxColor2 ;
24+ }
25+
26+ return result ;
27+ }
28+
29+ private List <List <Integer >> buildGraph (int [][] edges , int size ) {
30+ List <List <Integer >> graph = new ArrayList <>();
31+ for (int i = 0 ; i < size ; i ++) graph .add (new ArrayList <>());
32+ for (int [] edge : edges ) {
33+ int u = edge [0 ], v = edge [1 ];
34+ graph .get (u ).add (v );
35+ graph .get (v ).add (u );
36+ }
37+ return graph ;
38+ }
39+
40+ private void bfs (List <List <Integer >> graph , int [] colorCount , int [] nodeColor ) {
41+ int n = graph .size ();
42+ boolean [] visited = new boolean [n ];
43+ Queue <int []> queue = new LinkedList <>();
44+ queue .offer (new int []{0 , 0 });
45+ visited [0 ] = true ;
46+
47+ while (!queue .isEmpty ()) {
48+ int [] curr = queue .poll ();
49+ int node = curr [0 ], color = curr [1 ];
50+ nodeColor [node ] = color ;
51+ colorCount [color ]++;
52+
53+ for (int neighbor : graph .get (node )) {
54+ if (!visited [neighbor ]) {
55+ visited [neighbor ] = true ;
56+ queue .offer (new int []{neighbor , 1 - color });
57+ }
58+ }
59+ }
60+ }
61+ }
0 commit comments