본문 바로가기

개발/algorithm

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

문제 설명

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

풀이 

  • 처음엔 bfs로 풀이. 시간초과 
# bfs 풀이 - 시간 초과 
from collections import deque

def solution(n, edge):
    answer = 0
    graph = [ [0]*(n+1) for _ in range(n+1) ]
    
    q = deque()

    distance = [0] * (n+1)

    for a, b in edge:
        graph[a][b] = graph[b][a] = 1 
    
    q.append(1)
    distance[1] = 0
    
    while q :
        v = q.popleft()
        for i in range(1,n+1):
            if graph[v][i] == 1 and distance[i] == 0:
                distance[i] = distance[v] + 1 
                q.append(i)
                
    distance = distance[2:]
    
    return distance.count(max(distance))
  • 다익스트라로 해결 
import heapq
INF = int(1e9)

def solution(n, edge):

  graph = [ [] for _ in range(n+1)]
  distance = [INF] * (n+1)

  for c,d in edge:
      graph[c].append((d,1))
      # 양방향으로 해줘야함 
      graph[d].append((c,1)) 

  q = []
  heapq.heappush(q, (0,1))
  distance[1] = 0
  
  while q :
    # 가장 최단거리가 짧은 노드에 대한 정보 꺼내기 
    dist, now = heapq.heappop(q)
    # 이미 처리된 적이 있으면 무시 
    if distance[now] < dist :
      continue
    for i in graph[now]:
      cost = dist + i[1]
      if cost < distance[i[0]]:
        distance[i[0]] = cost
        heapq.heappush(q, (cost,i[0]))
        
  # 0이랑 1번 노드 제외 
  distance = distance[2:]
  
  return distance.count(max(distance))