알고리즘 : DFS

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

public class Main {
	private int computers;
	private int numOfPair;
	private final int MAX = 105;
	private boolean[][] conn = new boolean[MAX][MAX];
	private boolean[] visited = new boolean[MAX];
	private int totalCnt = 0;
	public static void main(String[] args) throws Exception {
		Main main = new Main();
		main.start();	
	}
	
	private void start() throws Exception {
		System.setIn(new FileInputStream("src/웜바이러스/input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		computers = Integer.parseInt(br.readLine());
		numOfPair = Integer.parseInt(br.readLine());
		StringTokenizer st;
		for(int i =0 ;i<numOfPair; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			int p1 = Integer.parseInt(st.nextToken());
			int p2 = Integer.parseInt(st.nextToken());
			conn[p1][p2] = true;
			conn[p2][p1] = true;
		}
		dfs(1);
		System.out.println(totalCnt);
		br.close();
	}
	private void dfs(int start) {
		for(int i = 2; i <= computers; i++) {
			if(conn[start][i] && !visited[i]) {
				visited[i] = true;
				totalCnt++;
				dfs(i);
			}
		}
	}
}

출처

- https://www.acmicpc.net/problem/2606

+ Recent posts