ํ๋ก๊ทธ๋๋จธ์ค Level2 : ์ํด๋ฆฌ ์ฑ๋ฆฐ์ง ์ ๋ ฅ๋ง์ ๋๋ก ๋๋๊ธฐ
import java .util .Queue ;
import java .util .LinkedList ;
class Solution {
//(๋ฃจํธ ์ก์ ํ, ๋์ด์ง ์ ์ ๋ฒํธ(index), ์ ์ฒด ์ ๋ ฅ๋ง)
private int sizeOfTree (int root , int cut , int [][] wires ){
Queue <Integer > queue = new LinkedList <>();
int l = wires .length ;
boolean [] check = new boolean [l ]; //ํ์ธํ ์ ์
int curr = 0 ; // ๋ณด๊ณ ์๋ ์ก์ ํ
int size = 0 ; // ์ ๋ ฅ๋ง์ ์ก์ ํ ๊ฐฏ์
check [cut ] = true ;
queue .offer (root );
while (!queue .isEmpty ()){
curr = queue .poll ();
size ++;
for (int i =0 ; i <l ; i ++){
if (check [i ]){
continue ;
} else if (wires [i ][0 ]==curr ){
queue .offer (wires [i ][1 ]);
check [i ] = true ;
} else if (wires [i ][1 ]==curr ){
queue .offer (wires [i ][0 ]);
check [i ] = true ;
}
}
}
return size ;
}
public int solution (int n , int [][] wires ) {
int answer = -1 ;
int l = wires .length ;
int treeSize ;
int abs ;
// wire๊ฐ ๋์ด์ก์๋ ์๊ธด ๋๊ฐ์ ์ ๋ ฅ๋ง์ ํฌ๊ธฐ
for (int i =0 ; i <l ; i ++){
treeSize = sizeOfTree (wires [i ][0 ],i ,wires );
abs = Math .abs ((n - treeSize )-treeSize );
// ์ฐจ์ด๊ฐ ๊ฐ์ฅ ์์์ง ํ์ธ
if (answer <0 || answer > abs ){
answer = abs ;
}
}
return answer ;
}
}