-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path9372.java
74 lines (60 loc) · 1.82 KB
/
9372.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.*;
import java.util.*;
public class Main {
private static int N, M;
private static boolean[] visited;
private static ArrayList<Integer>[] plane;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
plane = new ArrayList[N + 1];
for (int i = 1; i <= N; i++) {
plane[i] = new ArrayList<Integer>();
}
for (int i = 1; i <= M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
plane[a].add(b);
plane[b].add(a);
}
visited = new boolean[N + 1];
sb.append(dfs(1)).append("\n"); // 방법 1
sb.append(bfs(1) - 1).append("\n"); // 방법 2
sb.append((N - 1)).append("\n"); // 방법 3 (최소 신장 트리의 성질 : 간선의 개수 == 정점의 개수 - 1)
}
System.out.println(sb.toString());
}
private static int dfs(int start) {
visited[start] = true;
int count = 0;
for (int destination : plane[start]) {
if (!visited[destination]) {
count += dfs(destination) + 1;
}
}
return count;
}
private static int bfs(int start) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
visited[start] = true;
int count = 0;
while (!queue.isEmpty()) {
count++;
int current = queue.poll();
for (int destination : plane[current]) {
if (!visited[destination]) {
visited[destination] = true;
queue.add(destination);
}
}
}
return count;
}
}