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;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 짝수와 홀수 (JAVA) (0) | 2022.06.26 |
---|---|
프로그래머스 가운데 글자 가져오기 (JAVA) (0) | 2022.06.25 |
프로그래머스 [3차] 압축 (JAVA) (0) | 2022.06.23 |
프로그래머스 섬 연결하기 (JAVA) (0) | 2022.06.22 |
프로그래머스 입국심사 (JAVA) (0) | 2022.06.21 |