프로그래머스 - 그래프 - 가장 먼 노드

2021. 3. 29. 15:59Algorithm

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
 
public class 가장_먼_노드 {
    public static void main(String[] args) {
        가장_먼_노드 o = new 가장_먼_노드();
        System.out.println(o.solution(6new int[][]{{36}, {43}, {32}, {13}, {12}, {24}, {52}}));
        //System.out.println(o.solution(2, new int[][]{{1, 2}}));
        //System.out.println(o.solution(4, new int[][]{{4, 3}, {1, 3}, {2, 3}}));
    }
 
    public int solution(int n, int[][] edge) {
        List<List<Integer>> adList = new ArrayList<>();
 
        for(int i=0; i<n+1; i++) {
            adList.add(new ArrayList<>());
        }
 
        for(int i=0; i<edge.length; i++) {
            adList.get(edge[i][0]).add(edge[i][1]);
            adList.get(edge[i][1]).add(edge[i][0]);
        }
 
        return getCountOfDistantNodeByBFS(adList);
    }
 
    private int getCountOfDistantNodeByBFS(List<List<Integer>> adList) {
        Queue<Integer> q = new LinkedList<>();
        boolean[] isVisit = new boolean[adList.size()];
        Integer[] dist = new Integer[adList.size()];
        Arrays.fill(dist, Integer.MAX_VALUE);
 
        q.offer(1);
        dist[1= 0;
        dist[0= Integer.MIN_VALUE;
 
        while (!q.isEmpty()) {
            int curNode = q.poll();
            isVisit[curNode] = true;
 
            for(int nextNode : adList.get(curNode)) {
                if(!isVisit[nextNode] && dist[nextNode] > dist[curNode] + 1) {
                    q.offer(nextNode);
                    dist[nextNode] = dist[curNode] + 1;
                }
            }
        }
 
        Arrays.sort(dist);
        int maxValue = dist[dist.length-1];
        int count = 0;
        for(int i=dist.length-1; i>=0; i--) {
            if(dist[i].equals(maxValue)) {
                count++;
            } else {
                break;
            }
        }
 
        return count;
    }
}
 
cs

 

알고리즘

  • BFS
  • BFS로 모든 노드를 순회한다.
  • 이때 최단거리를 찾기위해 다음 노드의 거리가 현 노드의 거리 +1보다 크면 다음 노드의 최단거리를 현 노드의 거리 + 1로 업데이트해준다.
  • 최단거리 배열을 정렬하여 가장 큰 값과 같은 값의 갯수를 출력해준다.

'Algorithm' 카테고리의 다른 글

백준 - 2776 - 암기왕  (0) 2021.03.30
백준 - 10816 - 숫자 카드2  (0) 2021.03.29
백준 - 13913 - 숨바꼭질4  (0) 2021.03.27
백준 - 13549 - 숨바꼭질3  (0) 2021.03.27
백준 - 12851 - 숨바꼭질2  (0) 2021.03.26