알고리즘 : 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);
}
}
}
}
출처
'알고리즘' 카테고리의 다른 글
그래프/Strongly Connected Component 백준 2150번 (1) | 2023.09.17 |
---|---|
DP/1,2,3 더하기 백준 9095번 (0) | 2022.10.09 |
스택/괄호의값 백준 2504번 (0) | 2022.02.13 |
스택/괄호 백준 9012번 (0) | 2022.02.10 |
매개변수탐색/나무 자르기 백준 2805번 (0) | 2022.01.30 |