[프로그래머스] 가장 먼 노드 (BFS)

2025. 5. 7. 12:41·Algorithm/Coding Test Records

문제 소개

오늘 풀었던 프로그래머스 - 가장 먼 노드 문제를 정리합니다.

이 문제는 1번 노드를 시작점으로 해서, 가장 멀리 떨어진 노드(최단 거리 기준)의 개수를 구하는 문제입니다.
즉, BFS(너비 우선 탐색) 을 통해 그래프에서 최장 레벨에 위치한 노드 개수를 세는 문제입니다.

문제 링크: 가장 먼 노드 - 프로그래머스


문제 접근 방식

이 문제는 다음과 같은 방식으로 접근했습니다:

  1. 무방향 그래프를 인접 리스트로 구성
  2. 1번 노드에서 BFS를 수행해, 다음 노드를 큐에 저장
  3. 각 거리(깊이)별 노드 수(que.size()) 중 마지막 노드 수를 반환

해결 과정 및 코드

핵심 아이디어

  1. BFS 탐색을 통해 1번 노드에서 같은 거리에 있는 모든 노드를 구할 수 있음
  2. 탐색 도중 가장 마지막 레벨(깊이)에서 탐색된 노드들의 수가 정답

코드

시간 복잡도 :O(N + E)

  • N = 노드 수 (최대 20,000), E = 간선 수 (최대 50,000)
  • BFS 탐색과 인접 리스트 구성 모두 선형 시간 내 해결 가능
import java.util.*;

class Solution {
    // 그래프 노드 클래스
    class Node {
        int no;
        Node next;        
        Node (int no, Node next) {
            this.no = no;
            this.next = next;
        }
    }
    
    public int solution(int n, int[][] edge) {
        Node [] graph = new Node [n+1];
        for (int i = 0; i < edge.length; i++) {
            int from = edge[i][0];
            int to = edge[i][1];
            // 무방향 그래프
            graph[from] = new Node(to, graph[from]);
            graph[to] = new Node(from, graph[to]);
        }
        
        // bfs
        ArrayDeque<Integer> que = new ArrayDeque<>();
        boolean[] visited = new boolean[n+1];
        que.offer(1);
        visited[1] = true;
        int countAtMaxDepth = 1;
        while(!que.isEmpty()) {
            countAtMaxDepth = que.size(); // 현재 깊이의 노드 수 저장
            for (int size = que.size(); size > 0; size--) {
                int cur = que.poll();
                for (Node temp = graph[cur]; temp != null; temp = temp.next) {
                    if (visited[temp.no]) continue;
                    visited[temp.no] = true;
                    que.offer(temp.no);
                }
                
            }
        }
        return countAtMaxDepth;
    }
}

'Algorithm > Coding Test Records' 카테고리의 다른 글

[프로그래머스] 전화번호 목록 (Hash)  (0) 2025.05.12
[프로그래머스] 폰켓몬 (Hash)  (0) 2025.05.11
[프로그래머스] 이중우선순위큐 (Heap)  (0) 2025.05.10
[프로그래머스] 디스크 컨트롤러 (Heap)  (0) 2025.05.09
[프로그래머스] 더 맵게 (Heap)  (1) 2025.05.08
'Algorithm/Coding Test Records' 카테고리의 다른 글
  • [프로그래머스] 폰켓몬 (Hash)
  • [프로그래머스] 이중우선순위큐 (Heap)
  • [프로그래머스] 디스크 컨트롤러 (Heap)
  • [프로그래머스] 더 맵게 (Heap)
Celion
Celion
오늘도 평소처럼 화이팅!
  • Celion
    Orion Log
    Celion
  • 전체
    오늘
    어제
    • 전체 글 (144)
      • Uncompiled Thoughts (8)
        • 네이버 부스트캠프 10기 (5)
      • CS 기초부터 한 걸음씩 (34)
      • Code Odyssey (22)
      • Algorithm (77)
        • Coding Test Records (63)
      • Git (3)
      • reference (0)
  • 블로그 메뉴

    • 태그
    • 방명록
  • 태그

    boostcamp
    코테
    Level3
    greedy
    java
    프로그래머스
    시뮬레이션
    알고리즘고득점kit
    백준
    Kotlin
    문법정리
    Level2
  • 최근 글

  • 인기 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.4
Celion
[프로그래머스] 가장 먼 노드 (BFS)
상단으로

티스토리툴바