728x90
SMALL
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import heapq
def solution(N, road, K):
def dijkstra():
heap = []
heapq.heappush(heap, (start, 0))
costs[start] = 0
while heap:
node, cost = heapq.heappop(heap)
if costs[node] < cost:
continue
for next_node, weight in graph[node]:
next_cost = cost + weight
if next_cost < costs[next_node]:
costs[next_node] = next_cost
path[next_node] = node
heapq.heappush(heap, (next_node, next_cost))
start = 1
graph = [[] for _ in range(N+1)]
costs = [float('inf')] * (N+1)
path = [0] * (N+1)
for r in road:
u, v, w = r
graph[u].append((v, w))
graph[v].append((u, w))
dijkstra()
return sum(1 for cost in costs if cost <= K)
- 전형적인 Dijkstra 알고리즘 문제입니다.
- 구조만 외워두면 음의 간선을 포함하지 않는 가중치 그래프에서의 최단 거리를 쉽게 계산할 수 있습니다!
- 그래프 탐색 시간 효율성을 위해 heapq를 이용한 우선순위 큐를 도입하였습니다.
728x90
LIST
'알고리즘 문제 > 프로그래머스 (Level 2)' 카테고리의 다른 글
📗 행렬 테두리 회전하기 (2) | 2024.09.05 |
---|---|
📗 방금그곡 (6) | 2024.08.28 |
📗 숫자 카드 나누기 (0) | 2024.08.05 |
📗 메뉴 리뉴얼 (0) | 2024.07.26 |
📗 마법의 엘리베이터 (0) | 2024.07.23 |