ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로그래머스 - 가장 먼 노드
    취업 준비/알고리즘 2025. 1. 9. 10:25
    문제 설명

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

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

    제한사항
    • 노드의 개수 n은 2 이상 20,000 이하입니다.
    • 간선은 양방향이며 총 1개 이상 50,000개 이하의 간선이 있습니다.
    • vertex 배열 각 행 [a, b]는 a번 노드와 b번 노드 사이에 간선이 있다는 의미입니다.
    입출력 예nvertexreturn
    6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3
    입출력 예 설명

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

    import java.util.*;
    
    class Solution {
        static List<List<Integer>> graph;
        static boolean[] visited;
    
        public int solution(int n, int[][] edge) {
            // 그래프 초기화 (인접 리스트 사용)
            graph = new ArrayList<>();
            for (int i = 0; i <= n; i++) {
                graph.add(new ArrayList<>());
            }
    
            for (int[] line : edge) {
                int left = line[0];
                int right = line[1];
                graph.get(left).add(right);
                graph.get(right).add(left);
            }
    
            // BFS 실행
            return bfs(1, n);
        }
    
        static public int bfs(int start, int n) {
            visited = new boolean[n + 1];
            Queue<int[]> queue = new LinkedList<>();
            queue.add(new int[]{start, 0}); // {노드, 깊이}
            visited[start] = true;
    
            int maxDepth = 0;
            int count = 0;
    
            while (!queue.isEmpty()) {
                int[] current = queue.poll();
                int node = current[0];
                int depth = current[1];
    
                // 최대 깊이 갱신 및 개수 계산
                if (depth > maxDepth) {
                    maxDepth = depth;
                    count = 1; // 새로운 깊이의 첫 노드
                } else if (depth == maxDepth) {
                    count++;
                }
    
                // 인접 노드 탐색
                for (int neighbor : graph.get(node)) {
                    if (!visited[neighbor]) {
                        visited[neighbor] = true;
                        queue.add(new int[]{neighbor, depth + 1});
                    }
                }
            }
    
            return count;
        }
    }



    '취업 준비 > 알고리즘' 카테고리의 다른 글

    프로그래머스 - 올바른 괄호  (6) 2025.01.10
    프로그래머스 - 기능개발  (2) 2025.01.10
    프로그래머스 - 입국심사  (5) 2025.01.08
    프로그래머스 - 체육복  (4) 2025.01.07
    프로그래머스 - 더 맵게  (1) 2025.01.06
Designed by Tistory.