프로그래머스_가장 먼 노드_그래프(java)

2019. 3. 21. 22:37알고리즘문제/프로그래머스

가장 먼 노드


1. 문제

https://programmers.co.kr/learn/courses/30/lessons/49189



n개의 노드가 있는 그래프가 있습니다. 노드는 1부터 n까지 번호가 적혀있습니다. 1 노드에서 가장 멀리 떨어진 노드의 갯수를 구하려고 합니다. 가장 멀리 떨어진 노드란 최단경로로 이동했을 간선의 개수가 가장 많은 노드들을 의미합니다.


노드의 개수 n, 간선에 대한 정보가 담긴 2차원 배열 vertex 매개변수로 주어질 , 1 노드로부터 가장 멀리 떨어진 노드가 개인지를 return 하도록 solution 함수를 작성해주세요.




solution - 1) 그래프의 인접리스트 이용 (ArrayList) _ (BFS)


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
import java.util.*;
 
class Solution {
    public int solution(int n, int[][] edge) {
        ArrayList<ArrayList<Integer>> list = new <ArrayList<Integer>> ArrayList();
        Queue<Integer> q = new LinkedList<Integer>();
        for(int i = 0; i < edge.length; i++) {
            list.add(new ArrayList<Integer>()); 
        }
        for(int i = 0; i < edge.length; i++) {
            int m = edge[i][0];
            int h = edge[i][1];
            list.get(m).add(h);
            list.get(h).add(m);
        }
 
        int[] d = new int[n+1];
        Arrays.fill(d, -1);
        
        d[1= 0;
        q.add(1);
        int u = 0;
        while(q.size() > 0) {
            u = q.poll();
            for(int e : list.get(u)) {
                if(d[e] == -1) {
                    d[e] = d[u]+1;
                    q.add(e);
                }
            }
            
        }
        
        int count = 0;
        int max = d[0];
        for(int i : d) {
            if(max < i) {
                max = i;
                count = 1;
            }else if(max == i){
                count++;
            }
        }
        return count;
    }
}
cs