백준
백준 5567 결혼식(Java)
Park DJ
2023. 2. 10. 22:31
https://www.acmicpc.net/problem/5567
5567번: 결혼식
예제 1의 경우 2와 3은 상근이의 친구이다. 또, 3과 4는 친구이기 때문에, 4는 상근이의 친구의 친구이다. 5와 6은 친구도 아니고, 친구의 친구도 아니다. 따라서 2, 3, 4 3명의 친구를 결혼식에 초대
www.acmicpc.net
Java 코드
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
static int count = 0;
static int n;
static int m;
static ArrayList<ArrayList<Integer>> list;
static boolean[] visit;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
list = new ArrayList<>();
visit = new boolean[n + 1];
for(int i = 0; i <= n; i++) list.add(new ArrayList<>());
for(int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
list.get(a).add(b);
list.get(b).add(a);
}
dfs(0, 1);
for(int i = 2; i <= n; i++) {
if(visit[i] == true) count++;
}
System.out.println(count);
}
public static void dfs(int dep, int start) {
if(dep == 2) return;
for(int i : list.get(start)) {
visit[i] = true;
dfs(dep + 1, i);
}
}
}