Skip to content

Latest commit

ย 

History

History
59 lines (50 loc) ยท 1.77 KB

File metadata and controls

59 lines (50 loc) ยท 1.77 KB

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 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;
    }
}