import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Solution {
public int solution(int n, int[][] edge) {
int answer = 0;
Queue<Node> queue=new LinkedList<>();
queue.add(new Node(1,0));
int[] minRoot=new int[n+1];
List<Node>[] graph=new ArrayList[n+1];
for (int i = 1; i <= n; i++) {
graph[i]=new ArrayList<>();
minRoot[i]=Integer.MAX_VALUE;
}
for (int[] ints : edge) {
graph[ints[0]].add(new Node(ints[1],1));
graph[ints[1]].add(new Node(ints[0],1));
}
boolean[] isVisited=new boolean[n+1];
while (!queue.isEmpty()){
Node node = queue.poll();
isVisited[node.idx]=true;
for (Node newNode : graph[node.idx]) {
if(!isVisited[newNode.idx]&& minRoot[newNode.idx]> node.cost+ newNode.cost){
minRoot[newNode.idx]=node.cost+ newNode.cost;
queue.add(new Node(newNode.idx, minRoot[newNode.idx]));
}
}
}
int maxRoot=-1;
int maxNum=0;
for (int i = 2; i <= n; i++) {
if(minRoot[i]>maxRoot){
maxNum=1;
maxRoot=minRoot[i];
}else if(minRoot[i]==maxRoot)
maxNum++;
}
return maxNum;
}
class Node{
int idx;
public Node(int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
int cost;
}
}
일반적인 다익스트라 문제였다.
보자마자, 다익스트라 라고 생각될 만큼 명확한 문제였지만, 다익스트라 자체를 좀오랜만에 풀어봐서 그런지 헷갈렸던 것 같다.
'Algorithm > Programmers' 카테고리의 다른 글
[Lv.3] 공 이동 시뮬레이션 - 자바 (0) | 2023.07.13 |
---|---|
[Lv.3] 모두 0으로 만들기 (0) | 2023.07.13 |
[Lv.3] 카드 짝 맞추기 -자바 (0) | 2023.07.07 |
[Lv.3] 스타 수열 -자바 (0) | 2023.07.07 |
[Lv.3] 기둥과 보 설치 - 자바 (0) | 2023.07.07 |