`비선형 자료구조인 graph를 구현하여 DFS를 해보는 문제
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
|
public class B2606_바이러스 {
static ArrayList<Integer>[] a;
static boolean[] visit;
static int count;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
a = new ArrayList[n+1];
visit = new boolean[n+1];
for (int i=1; i<=n; i++) {
a[i] = new ArrayList<Integer>();
}
// 연결 된 부분 정보 저장
for(int i=0;i<m;i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
a[start].add(end);
a[end].add(start);
}
count=0;
// 1번부터 탐색
search(1);
System.out.println(count);
}
// 연결된 부분 탐색
public static void search(int x) {
visit[x] = true;
for (int y : a[x]) {
if (visit[y] == false) {
count++;
search(y);
}
}
}
}
|