728x90
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
|
import java.io.*;
import java.util.*;
public class Main {
static int nV, nE;
static int ad[][];
static boolean visit[];
static int component = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
nV = Integer.parseInt(st.nextToken());
nE = Integer.parseInt(st.nextToken());
ad = new int[nV+1][nV+1];
visit = new boolean[nV+1];
for(int i = 0; i < nE; i++){
st = new StringTokenizer(br.readLine());
int s1 = Integer.parseInt(st.nextToken());
int s2 = Integer.parseInt(st.nextToken());
ad[s1][s2] = ad[s2][s1] = 1;
}
for(int i = 1; i <= nV; i++){
component += bfs(i);
}
System.out.println(component);
}
static int bfs(int start){
Queue<Integer> q = new LinkedList<>();
q.offer(start);
if(visit[start]) return 0;
visit[start] = true;
while(!q.isEmpty()){
start = q.poll();
for(int i = 1; i <= nV; i++){
if(!visit[i] && ad[start][i] == 1) {
q.offer(i);
visit[i] = true;
}
}
}
return 1;
}
}
|
cs |
이 문제는 bfs함수를 int로 반환해주고, bfs가 돌아가면 1을 리턴해주고, bfs가 실행이 안되면 0을 리턴해주는 방식으로, component의 개수를 구했다.
728x90
'BOJ(Java)' 카테고리의 다른 글
자바(백준) 1697 숨바꼭질 (0) | 2021.01.04 |
---|---|
자바(백준) 1389 케빈 베이컨의 6단계 법칙 (0) | 2020.12.30 |
자바(백준) 7562 나이트의 이동 (0) | 2020.12.30 |
자바(백준) 4963 섬의 개수 (0) | 2020.12.30 |
자바(백준) 3184 양 (0) | 2020.12.30 |