[BFS / DFS] [백준 / 2606 ] 실버1 - 바이러스 (java/자바)

package newboj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class boj_2606 {
static int computerCount;
static int linkCase;
static boolean isVisited[];
static int infectedCount = 0; // 바이러스에 걸린 컴퓨터의 수를 세는 전역 변수
static List<Integer>[] matrix;
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
computerCount = Integer.parseInt(r.readLine());
linkCase = Integer.parseInt(r.readLine());
matrix = new ArrayList[computerCount+1];
isVisited = new boolean[computerCount+1];
for(int i=0; i<computerCount+1; i++){
matrix[i] = new ArrayList<>();
}
for(int i=0; i<linkCase; i++){
StringTokenizer st = new StringTokenizer(r.readLine());
int computer1 = Integer.parseInt(st.nextToken());
int computer2 = Integer.parseInt(st.nextToken());
matrix[computer1].add(computer2);
matrix[computer2].add(computer1);
}
dfs(1);
System.out.println(infectedCount - 1); // 1번 컴퓨터를 제외한 수를 출력
}
static void dfs(int startComputer){
isVisited[startComputer] =true;
infectedCount++; // 방문할 때마다 바이러스에 걸린 컴퓨터 수 증가
for(int i=0; i<matrix[startComputer].size();i++){
if(!isVisited[matrix[startComputer].get(i)]){
isVisited[matrix[startComputer].get(i)] =true;
dfs(matrix[startComputer].get(i));
}
}
}
}