●문제 출처
●정리(요약)
지민이는 세계에서 가장 유명한 사람이 누구인지 궁금해졌다. 가장 유명한 사람을 구하는 방법은 각 사람의 2-친구를 구하면 된다. 어떤 사람 A가 또다른 사람 B의 2-친구가 되기 위해선, 두 사람이 친구이거나, A와 친구이고, B와 친구인 C가 존재해야 된다. 여기서 가장 유명한 사람은 2-친구의 수가 가장 많은 사람이다. 가장 유명한 사람의 2-친구의 수를 출력하는 프로그램을 작성하시오.
A와 B가 친구면, B와 A도 친구이고, A와 A는 친구가 아니다.
●코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static int N;
static char[][] friends;
static boolean[] visited;
static int result = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
friends = new char[N][N];
for (int i = 0; i < N; i++) {
friends[i] = br.readLine().toCharArray();
}
for (int i = 0; i < N; i++) {
visited = new boolean[N];
visited[i] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(i);
int depth = 0;
int count = 0;
while (depth < 2) {
int size = queue.size();
for (int j = 0; j < size; j++) {
int n = queue.poll();
for (int k = 0; k < N; k++) {
if (friends[n][k] == 'Y' && !visited[k]) {
queue.add(k);
visited[k] = true;
count++;
}
}
}
depth++;
}
result = Math.max(result, count);
}
System.out.println(result);
}
}
●느낀 점
