[백준] P9372

동민·2021년 3월 11일
0
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class P9372 {

	static int[][] matrix;
	static boolean[] visit;
	static int t, n, m, v1, v2;

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		t = sc.nextInt();

		int result[] = new int[t];

		for (int k = 0; k < t; k++) {

			n = sc.nextInt();
			m = sc.nextInt();

			matrix = new int[n + 1][n + 1];
			visit = new boolean[n + 1];

			for (int i = 1; i <= m; i++) {

				v1 = sc.nextInt();
				v2 = sc.nextInt();

				matrix[v1][v2] = matrix[v2][v1] = 1;

			}

			result[k] = bfs(1);

			resetVisit();
		}

		for (int i = 0; i < t; i++) {
			System.out.println(result[i]);
		}

		sc.close();
	}

	public static int bfs(int s) {
		Queue<Integer> queue = new LinkedList<Integer>();

		queue.add(s);
		visit[s] = true;

		int count = 0;

		while (!queue.isEmpty()) {
			s = queue.poll();
			for (int i = 1; i < n + 1; i++) {
				if (matrix[s][i] == 1 && !visit[i]) {
					queue.offer(i);
					visit[i] = true;
					count++;
				}
			}
		}
		return count;

	}

	public static void resetVisit() {

		for (int i = 1; i < n + 1; i++) {
			visit[i] = false;
		}

	}

}
profile
BE Developer

0개의 댓글