본문 바로가기

Algorithm

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

문제 설명

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

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

제한사항

  • 노드의 개수 n은 2 이상 20,000 이하입니다.
  • 간선은 양방향이며 총 1개 이상 50,000개 이하의 간선이 있습니다.
  • vertex 배열 각 행 [a, b]는 a번 노드와 b번 노드 사이에 간선이 있다는 의미입니다.

입출력 예

n vertex return
6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3

입출력 예 설명

예제의 그래프를 표현하면 아래 그림과 같고, 1번 노드에서 가장 멀리 떨어진 노드는 4,5,6번 노드입니다.

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


내 소스

import java.util.*;

class Solution {
    public int solution(int n, int[][] edge) {
        int answer = 0;
        int cur;
        int next=0;
        boolean found;
        int max;
        int[] depth = new int[n+1];
        boolean[] visited = new boolean[n+1];
        int i;
        Queue<Integer> q = new LinkedList<Integer>();

        Arrays.fill(depth, Integer.MAX_VALUE);
        depth[1] = 0;
        q.add(1);

        while(!q.isEmpty()){
            cur = q.poll();
            visited[cur] = true;
            for(i=0; i<edge.length; i++){
                found = false;
                if(edge[i][0] == cur){
                    next = edge[i][1];
                    found = true;
                }else if(edge[i][1] == cur){
                    next = edge[i][0];
                    found = true;
                }
                
                if(found && !visited[next]){
                    if(depth[next] == Integer.MAX_VALUE){
                        depth[next] = depth[cur]+1;
                    }else{
                        depth[next] = Math.min(depth[next], depth[cur]+1);
                    }
                    
                    visited[next] = true;
                    q.add(next);
                    
                }
            }
        }
        max = -1;
        for(i=2; i<n+1; i++){
            if(depth[i] != Integer.MAX_VALUE && (max < depth[i])){
                max = depth[i];
            }
        }
        for(i=2; i<n+1; i++){
            if(max == depth[i]){
                answer++;
            }
        }

        return answer;
    }
}