Algorithm

[BOJ 2606] 바이러스 ( with Java )

quedevel 2023. 4. 16. 14:15
728x90
반응형

문제

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net

제출한 답안

package BOJ;

import java.util.Scanner;

public class BOJ_2606 {
    private static int[][] graph;
    private static boolean[] isVisited;
    private static int M;
    private static int count = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        M = sc.nextInt();
        int N = sc.nextInt();

        graph = new int[M+1][M+1];
        isVisited = new boolean[M+1];

        for (int i = 0; i < N; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            graph[x][y] = graph[y][x] = 1; // 간선(Edge)
        }

        dfs(1);

        System.out.println(count-1);
        sc.close();
    }

    private static void dfs(int vertex){
        isVisited[vertex] = true;
        count++;

        for (int i = 1; i <= M; i++) {
            if (graph[vertex][i] == 1 && !isVisited[i]){
                isVisited[i] = true;
                dfs(i);
            }
        }
    }
}
728x90
반응형

'Algorithm' 카테고리의 다른 글

[BOJ 1012] 유기농 배추 ( with Java )  (0) 2023.04.16
[BOJ 2667] 단지번호붙이기 ( with Java )  (0) 2023.04.16
[BOJ 1260] DFS와 BFS ( with Java )  (0) 2023.04.16
LCA(Lowest Common Ancestor)  (1) 2023.04.15
DFS & BFS  (0) 2023.04.14