-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeek2_Day3.java
More file actions
52 lines (45 loc) · 1.17 KB
/
Week2_Day3.java
File metadata and controls
52 lines (45 loc) · 1.17 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
package Algorithm2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Week2_Day3 {
public static HashMap<Integer, HashSet<Integer>> graph;
public static Set<Integer> visit;
public static void main(String[] args) throws IOException {
graph = new HashMap<>();
visit = new HashSet<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] info = br.readLine().split(" ");
int N = Integer.parseInt(info[0]);
int M = Integer.parseInt(info[1]);
for(int j=1; j<=N; j++) {
graph.put(j, new HashSet<>());
}
for(int i=0; i<M; i++) {
String[] line = br.readLine().split(" ");
int N1 = Integer.parseInt(line[0]);
int N2 = Integer.parseInt(line[1]);
graph.get(N1).add(N2);
graph.get(N2).add(N1);
}
int count = 0;
for(int j=1; j<=N; j++) {
if(!visit.contains(j)) {
count++;
dfs(j);
}
}
System.out.println(count);
}
public static void dfs(int now) {
visit.add(now);
for(int el : graph.get(now)) {
if(!visit.contains(el)) {
dfs(el);
}
}
}
}