알고리즘/백준 풀이(탐색)
백준 2606번 - 바이러스(DFS)
공부 기록장
2024. 2. 4. 19:24
https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하인 양의 정수이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍
www.acmicpc.net
위 문제는 1번 컴퓨터와 연결된 컴퓨터의 수를 찾는 문제로 DFS 로 문제 풀이를 하였다.
기존 DFS 함수에 count 변수를 추가하여 답을 추출하였다.
▶코드
import java.util.*;
import java.io.*;
public class Main {
static int N, M;
static int count=0;
static int Edge_arr[][];
static boolean Visited_arr[];
public static void DFS(int start){
Visited_arr[start]=true;
for(int i=1;i<=N;i++){
if(Edge_arr[start][i]==1&&Visited_arr[i]==false){
DFS(i);
count++;
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
M = Integer.parseInt(br.readLine());
Edge_arr = new int[101][101];
Visited_arr = new boolean[101];
for(int i=0;i<M;i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
Edge_arr[a][b]=Edge_arr[b][a]=1;
}
DFS(1);
System.out.println(count);
}
}