Dev.baelanche

[백준 5567] 결혼식 본문

Data Structure & Algorithm/PS - JAVA

[백준 5567] 결혼식

baelanche 2019. 4. 11. 20:31
반응형

 

 

그래프에서 인접노드를 찾는 문제이다.

 

상근이의 친구의 친구까지 카운트 해야 하므로 노드 1번에 연결된 노드의 수와 그 노드에 연결된 노드의 수를 세면 된다.

 

 

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int m = sc.nextInt();
        int a[][] = new int[n+1][n+1];
        boolean visited[] = new boolean[n+1];
        ArrayList<Integer> f = new ArrayList<Integer>();
        int cnt = 0;
        
        for(int i=0; i<m; i++) {
            int an = sc.nextInt();
            int bn = sc.nextInt();
            
            a[an][bn] = 1;
            a[bn][an] = 1;
            
            if(an == 1) {
                cnt++;
                f.add(bn);
                visited[bn] = true;
            }
        }
        
        for(int i : f) {
            for(int j=2; j<=n; j++) {
                if(a[i][j] == 1 && !visited[j]) {
                    cnt++;
                    visited[j] = true;
                }
            }
        }
        
        System.out.println(cnt);
        sc.close();
    }
}
반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 5212] 지구 온난화  (0) 2019.04.11
[백준 10539] 수빈이와 수열  (0) 2019.04.11
[백준 3053] 택시 기하학  (0) 2019.04.10
[백준 2798] 블랙잭  (0) 2019.04.10
[백준 8979] 올림픽  (0) 2019.04.10
Comments