-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2606.java
More file actions
56 lines (46 loc) · 1.46 KB
/
2606.java
File metadata and controls
56 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 백준 2606번 바이러스
* bfs/dfs 알고리즘
*/
import java.util.*;
import java.util.List;
import java.awt.*;
import java.io.*;
public class Main {
static List<List<Integer>> graph = new ArrayList<>();
static int dfs(int[] visited){
int cnt = 0;
Stack<Integer> stack = new Stack<>();
stack.push(1);
while(!stack.isEmpty()){
int node = stack.pop();
if(visited[node]==0){
visited[node]=1;
cnt++;
for(int n : graph.get(node)){
if(visited[n]==0){
stack.push(n);
}
}
}
}
return cnt;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int computer = Integer.parseInt(br.readLine());
int e = Integer.parseInt(br.readLine());
for(int i=0; i<=computer; i++){
graph.add(new ArrayList<>());
}
for(int i=0; i<e; i++){
StringTokenizer st = new StringTokenizer(br.readLine()," ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph.get(a).add(b);
graph.get(b).add(a); // 양방향 그래프
}
int visited[] = new int[computer+1];
System.out.println(dfs(visited)-1);
}
}