-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ11724.java
More file actions
58 lines (48 loc) · 1.06 KB
/
Copy pathBOJ11724.java
File metadata and controls
58 lines (48 loc) · 1.06 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
57
58
package day7.graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BOJ11724 {
static int N, M;
static int cnt=0;
static ArrayList<Integer>[] adjList;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
N=sc.nextInt();
M=sc.nextInt();
adjList=new ArrayList[N+1];
visited=new boolean[N+1];
for (int i = 1; i < N+1; i++) {
adjList[i]=new ArrayList<>();
}
for (int i = 1; i < M+1; i++) {
int from=sc.nextInt();
int to=sc.nextInt();
adjList[from].add(to);
adjList[to].add(from);
}
for (int i = 1; i < N+1; i++) {
if(!visited[i]) {
BFS(i);
cnt++;
}
}
System.out.println(cnt);
}
private static void BFS(int start) {
Queue<Integer> queue=new LinkedList<>();
queue.offer(start);
visited[start]=true;
while(!queue.isEmpty()) {
int currNode=queue.poll();
for (int node : adjList[currNode]) {
if(!visited[node]) {
queue.offer(node);
visited[node]=true;
}
}
}
}
}