728x90
https://school.programmers.co.kr/learn/courses/30/lessons/12978
🐾 20221014
전형적인 다익스트라 문제 + 리스트 돌면서 k보다 작은 수 구해 return 하면 된다.
이 문제는 양방향이다!!
양방향인지 단방향인지 잘 보고 해야한다.
코드 :
import heapq
def dijkstra(distance,mp) :
q = []
# dist는 0, node 시작 번호는 1
heapq.heappush(q,[0,1])
distance[1] = 0
while q :
dist, node = heapq.heappop(q)
# 이미 저장되어 있는 값보다 크면 볼필요 없음
if distance[node] < dist : continue
# 지금 노드에서 갈 수 있는 노드를 모두 탐색
for i in mp[node] :
cost = dist + i[1]
# 지금 노드를 거쳐서 가는 값이 원래 값보다 작으면
if distance[i[0]] > cost :
# 갱신
distance[i[0]] = cost
heapq.heappush(q,[cost,i[0]])
def solution(N, road, K):
answer = 0
distance = [int(1e9)] * (N+1)
mp = [[] for _ in range(N+1)]
for u,v,w in road :
mp[u].append([v,w])
mp[v].append([u,w])
dijkstra(distance,mp)
for i in range(1,N+1) :
if distance[i] <= K : answer+=1
return answer
참고할 내 포스팅 :
https://what-am-i.tistory.com/400
반응형
'알고리즘 > 프로그래머스문제풀이' 카테고리의 다른 글
[Python/프로그래머스]아이템 줍기_(BFS) (0) | 2022.09.22 |
---|---|
[Python/프로그래머스]게임 맵 최단거리_(BFS) (0) | 2022.09.22 |
SQL_group,having,join (0) | 2022.09.21 |
[Python/프로그래머스]양궁대회_Bfs (1) | 2022.09.19 |
[Python/프로그래머스]k진수에서 소수 개수 구하기 (0) | 2022.09.19 |