[프로그래머스] 코딩테스트 연습 - 그래프 Level 3 가장 먼 노드

uoahy·2021년 9월 24일
0

Solution.java

import java.util.*;

class Solution {
    public int solution(int n, int[][] edge) {
        int answer = 0;
        
        ArrayList<Integer>[] arr = new ArrayList[n];
        
        // for (ArrayList a : arr) a = new ArrayList<>();
        
        for (int i = 0; i < n; i++) arr[i] = new ArrayList<>();
        
        for (int[] e : edge) {
            arr[e[0] - 1].add(e[1] - 1);
            arr[e[1] - 1].add(e[0] - 1);
        }
        
        Queue<Data> que = new LinkedList<>();
        boolean[] visited = new boolean[n];
        
        que.add(new Data(0, 0));
        visited[0] = true;
        
        int max = 0;
        while (!que.isEmpty()) {
            Data data = que.poll();
            
            for (Integer i : arr[data.i]) {
                if (!visited[i]) {
                    visited[i] = true;
                    que.add(new Data(i, data.distance + 1));
                    
                    if (data.distance > max) {
                        max = data.distance;
                        answer = 0;
                    }
                    
                    answer++;
                }
            }
        }
        
        return answer;
    }
}

class Data {
    int i;
    int distance;
    
    Data(int i, int distance) {
        this.i = i;
        this.distance = distance;
    }
}

ArrayList 배열을 초기화해주는 과정에서 foreach문으로 하였더니 초기화가 되지 않았다.

짐작가는 이유가 있긴한데 다음에 원인을 한 번 찾아봐야겠다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글