백준

백준 5567번 결혼식 (java)

대기업 가고 싶은 공돌이 2024. 8. 18. 03:18

[Silver II] 결혼식 - 5567

문제 링크

성능 요약

메모리: 20124 KB, 시간: 176 ms

분류

그래프 이론, 그래프 탐색

제출 일자

2024년 8월 18일 02:29:59

문제 설명

상근이는 자신의 결혼식에 학교 동기 중 자신의 친구와 친구의 친구를 초대하기로 했다. 상근이의 동기는 모두 N명이고, 이 학생들의 학번은 모두 1부터 N까지이다. 상근이의 학번은 1이다.

상근이는 동기들의 친구 관계를 모두 조사한 리스트를 가지고 있다. 이 리스트를 바탕으로 결혼식에 초대할 사람의 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 상근이의 동기의 수 n (2 ≤ n ≤ 500)이 주어진다. 둘째 줄에는 리스트의 길이 m (1 ≤ m ≤ 10000)이 주어진다. 다음 줄부터 m개 줄에는 친구 관계 ai bi가 주어진다. (1 ≤ ai < bi ≤ n) ai와 bi가 친구라는 뜻이며, bi와 ai도 친구관계이다.

출력

첫째 줄에 상근이의 결혼식에 초대하는 동기의 수를 출력한다.

풀이

bfs로 탐색하며 한 차례 탐색했을 때의 노드들과 두 번째 탐색했을 때 노드들의 갯수를 세주면 된다.

 

전체 코드

public class Main {
    static int N, M, cnt = 0;
    static boolean visited[];
    static List<ArrayList<Integer>> edge = new ArrayList<>();

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        N = Integer.parseInt(br.readLine());
        M = Integer.parseInt(br.readLine());

        visited = new boolean[N + 1];

        for (int i = 0; i <= N; i++) {
            edge.add(new ArrayList<>());
        }

        for (int i = 0; i < M; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());

            edge.get(a).add(b);
            edge.get(b).add(a);
        }

        bfs();

        bw.write(String.valueOf(cnt));
        bw.flush();
    }

    public static void bfs() {
        Queue<int[]> queue = new LinkedList<>();

        queue.add(new int[] { 1, 0 });
        visited[1] = true;

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int node = current[0];
            int depth = current[1];

            if (depth == 2) {
                continue; // 깊이 2를 넘으면 탐색을 중지
            }

            for (int neighbor : edge.get(node)) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    queue.add(new int[] { neighbor, depth + 1 });
                    if (depth == 1 || depth == 0) {
                        cnt++; 
                    }
                }
            }
        }
    }
}