Roel Notebook

[Java] 백준 11724 연결된 요소의 개수

by Roel Downey
728x90
반응형

백준 11724 연결된 요소의 개수

 

 

문제 

- 문제 링크: 백준 11724 연결된 요소의 개수

 

 

 

풀이

import java.util.*;
import java.io.*;
class Main {
static boolean[][] graph;
static boolean[] visited;
static int n,m;
static int answer;
static void dfs(int idx) {
visited[idx] = true;
for (int num =1; num <=n; num++) {
if(!visited[num] && graph[idx][num])
dfs(num);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
graph = new boolean[n+1][n+1];
visited = new boolean[n+1];
visited[0] = true;
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][b] = true;
graph[b][a] = true;
}
for(int j=0; j<n+1; j++) {
if(visited[j]) {
continue;
}
dfs(j);
answer++;
}
bw.write(String.valueOf(answer));
br.close();
bw.close();
}
}



728x90
반응형
블로그의 프로필 사진

블로그의 정보

What doing?

Roel Downey

활동하기