ye0nn
영차영차
ye0nn
전체 방문자
오늘
어제
  • 분류 전체보기 (61)
    • CS (0)
      • 운영체제 (0)
      • 네트워크 (0)
      • 알고리즘 & 자료구조 (0)
    • 코딩테스트 (48)
      • 프로그래머스 (40)
      • 백준 (8)
    • 프로그래밍 (11)
      • 프론트엔드 (3)
      • 자바스크립트 (0)
      • 스위프트 (7)
      • 파이썬 (1)
    • 취준기록 (1)

인기 글

블로그 메뉴

  • 홈
  • 태그
  • 방명록

티스토리

hELLO · Designed By 정상우.
ye0nn

영차영차

[프로그래머스] Level 2 - 배달 (Python)
코딩테스트/프로그래머스

[프로그래머스] Level 2 - 배달 (Python)

2022. 6. 9. 12:56

 

 

 

 

https://programmers.co.kr/learn/courses/30/lessons/12978

 

코딩테스트 연습 - 배달

5 [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] 3 4 6 [[1,2,1],[1,3,2],[2,3,2],[3,4,3],[3,5,2],[3,5,3],[5,6,1]] 4 4

programmers.co.kr

 

 

 

 

✅ Solution

  • 한 정점으로부터 다른 모든 정점까지의 최단 거리를 구해야 하므로 다익스트라 알고리즘을 이용한다.
  • heapq를 이용하여 다익스트라 알고리즘을 구현한 뒤, K 이하의 거리를 가지는 정점의 수를 세어준다.
  • 양방향, 즉 a->b, b->a 모두 가능하므로 주의하면서 간선 정보를 처리한다.

 

 

 

 

✅ Code

import heapq


def dijkstra(start, graph, distance):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 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]))


def solution(N, roads, K):
    answer = 0
    INF = int(1e9)

    graph = [[] for _ in range(N + 1)]
    distances = [INF] * (N + 1)

    for road in roads:
        a, b, c = road
        graph[a].append((b, c))
        graph[b].append((a, c))

    dijkstra(1, graph, distances)

    for distance in distances:
        if distance <= K:
            answer += 1

    return answer

 

 

 

 

저작자표시 (새창열림)

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[프로그래머스] Level 2 - 위장 (Python)  (0) 2022.06.09
[프로그래머스] Level 2 - 게임 맵 최단거리 (Python)  (0) 2022.06.09
[프로그래머스] Level 2 - 괄호 회전하기 (Python)  (0) 2022.06.09
[프로그래머스] Level 2 - 짝지어 제거하기 (Python)  (0) 2022.06.04
[프로그래머스] Level 2 - 타겟 넘버 (Python)  (0) 2022.06.04
    '코딩테스트/프로그래머스' 카테고리의 다른 글
    • [프로그래머스] Level 2 - 위장 (Python)
    • [프로그래머스] Level 2 - 게임 맵 최단거리 (Python)
    • [프로그래머스] Level 2 - 괄호 회전하기 (Python)
    • [프로그래머스] Level 2 - 짝지어 제거하기 (Python)
    ye0nn
    ye0nn
    프론트엔드 개발자의 개발기록

    티스토리툴바