BFS
, 그래프
https://school.programmers.co.kr/learn/courses/30/lessons/49189
import java.util.*;
class Solution {
static List<List<Integer>> adjList = new ArrayList<>();
static boolean[] visited;
public int solution(int n, int[][] edge) {
visited = new boolean[n + 1];
for(int i=0; i<=n; i++) {
adjList.add(new ArrayList<>());
}
for(int[] adj : edge) {
int node1 = adj[0];
int node2 = adj[1];
adjList.get(node1).add(node2);
adjList.get(node2).add(node1);
}
return bfs(1);
}
public int bfs(int node) {
int maxDist = 1;
int answer = 0;
int dist = 1;
Queue<Integer> queue = new LinkedList<>();
visited[node] = true;
for(int movable : adjList.get(node)) {
visited[movable] = true;
maxDist = dist;
answer++;
queue.offer(movable);
}
while(!queue.isEmpty()) {
dist++;
int size = queue.size();
for(int i=0; i<size; i++) {
int curNode = queue.poll();
for(int movable : adjList.get(curNode)) {
if(!visited[movable]) {
if(maxDist < dist) {
answer = 0;
}
maxDist = dist;
answer++;
visited[movable] = true;
queue.offer(movable);
}
}
}
}
return answer;
}
}
30분