알고리즘
프로그래머스 가장 먼 노드 (JAVA)
박카스마시며코딩
2022. 6. 24. 13:46
https://programmers.co.kr/learn/courses/30/lessons/49189
코딩테스트 연습 - 가장 먼 노드
6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3
programmers.co.kr
저는 BFS를 통해 해당 문제를 해결하였습니다.
1부터 BFS를 진행하여 가장 먼 노드가 몇개인지를 판별하였습니다. time을 통해 각각의 노드가 1부터 시작해서 얼마나 떨어져있는지를 판단하였고, 가장 먼 노드의 개수를 세는 변수 result는 곧 size가 0이 아니면서 time이 가장 클 때의 Queue의 사이즈입니다.
import java.util.*;
class Solution {
private static final int START = 0;
private static final int END = 1;
private static final int START_POSITION = 1;
public int solution(int n, int[][] edges) {
int answer = 0;
List<Integer>[] map = new List[n+1];
for(int i = 0 ; i <= n ; i++){
map[i] = new ArrayList<>();
}
for(int[] edge : edges){
map[edge[START]].add(edge[END]);
map[edge[END]].add(edge[START]);
}
answer = bfs(map,n);
return answer;
}
private static int bfs(List<Integer>[] map, int n){
Queue<Integer> q = new LinkedList<>();
q.offer(START_POSITION);
boolean[] visited = new boolean[n+1];
visited[START_POSITION] = true;
int result = 0;
while(!q.isEmpty()){
int size = q.size();
result = size;
for(int i = 0 ; i < size ; i++){
int now = q.poll();
for(int next : map[now]){
if(!visited[next]){
visited[next] = true;
q.offer(next);
}
}
}
}
return result;
}
}