Roel Notebook

[Java] 백준 2606 바이러스

by Roel Downey
728x90
반응형

백준 2606 바이러스

 

 

문제 

- 문제 링크: 백준 2606 바이러스

 

 

 

풀이

import java.util.*;
import java.io.*;

class Main {
    static boolean[][] gragh;
    static boolean[] visited;
    static int n,m;
    static int answer;

    static void dfs(int idx) {
       visited[idx] = true;
       answer++;

       for (int num =1; num <=n; num++) {
           if(!visited[num] && gragh[idx][num])
               dfs(num);
       }
    }

    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());
        gragh = new boolean[n+1][n+1];
        visited = new boolean[n+1];
        m = Integer.parseInt(br.readLine());

        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());
            gragh[a][b] = true;
            gragh[b][a] = true;
        }

        dfs(1);

        bw.write(String.valueOf(answer-1));

        br.close();
        bw.close();
    }
}



728x90
반응형

블로그의 정보

What doing?

Roel Downey

활동하기