https://www.acmicpc.net/problem/11724
나의풀이
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int answer=0;
int n = Integer.parseInt(st.nextToken());//정점
int m = Integer.parseInt(st.nextToken());//간선
List<Integer>[] graph= new ArrayList[n+1];
boolean[] visited = new boolean[n+1];//방문여부 저장
for(int i=0; i<=n; i++){
graph[i]=new ArrayList<>();
}
for(int i=0 ; i<m; i++){
st = new StringTokenizer(br.readLine());
int a=Integer.parseInt(st.nextToken());
int b=Integer.parseInt(st.nextToken());
//양방향으로 넣어주기
graph[a].add(b);
graph[b].add(a);
}
for(int i=1; i<=n; i++){
if(visited[i] == false){//방문안한 경우만
Queue<Integer> q = new LinkedList<>();
q.offer(i);
while(!q.isEmpty()){
Integer temp=q.poll();
for(int j=0;j<graph[temp].size(); j++){
int next = graph[temp].get(j);
if(visited[next] == false){
visited[next] = true;
q.offer(next);
}
}
}
answer++;
}
}
bw.write(Integer.toString(answer));
bw.flush();
br.close();
bw.close();
}
}
'코테풀이' 카테고리의 다른 글
[백준] BOJ - 2644 촌수계산 java (실버2) (0) | 2023.04.12 |
---|---|
[백준] BOJ - 4963 섬의 개수 java (실버2) (0) | 2023.04.12 |
[백준] BOJ - 2075 N번째 큰 수 java (실버2) (0) | 2023.04.06 |
[백준] BOJ - 2304 창고 다각형 java (실버2) (0) | 2023.04.04 |
[백준] BOJ - 1522 문자열 교환 java 자바 풀이(실버1) (0) | 2023.04.04 |