DFS
import java.util.Scanner;
class Main {
// 재귀 함수는 전역 변수로
static boolean[][] graph;
static boolean[] visited;
static int N, M;
static int answer;
public static void main(String[] args) {
// 0. input 받기
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); // 컴퓨터 개수
M = sc.nextInt(); // 간선 개수
graph = new boolean[N+1][N+1];
visited = new boolean[N+1];
// 1. 그래프 정보 입력
int x,y;
for(int i=0; i<M; i++){
x = sc.nextInt();
y = sc.nextInt();
graph[x][y] = graph[y][x] = true;
}
// 2. dfs 및 결과 출력
dfs(1);
System.out.println(answer-1); // 1번 노드 제외한 수
sc.close();
}
public static void dfs(int idx) {
answer++; // 방문한 노드 개수 증가
visited[idx] = true; // 방문 노트 체크
for(int i=1; i<=N; i++){
if(!visited[i] && graph[idx][i]){
dfs(i);
}
}
}
}
참고 : 개발자로 취직하기 유튜브
'solve' 카테고리의 다른 글
| [프로그래머스] Lv2. 피로도 (자바) (0) | 2024.01.09 |
|---|---|
| [백준 1018] 체스판 다시 칠하기 (자바) (0) | 2024.01.09 |
| [백준 2667/실버1] 단지 번호 붙이기 (자바) (0) | 2024.01.09 |
| 두번째 코딩테스트 벼락치기(또다시..) (0) | 2024.01.08 |
| 코딩테스트 벼락치기(이게 맞나..) (1) | 2023.07.23 |