Skip to content

Commit 15e0042

Browse files
committed
Delivery route / 심화
1 parent f7e535e commit 15e0042

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 가중치 있는 무방향 그래프(중복간선 존재)
2+
// 다익스트라 알고리즘 활용
3+
// 1번에서 각 마을로 음식배달. K시간 이하로 배달 가능한 곳 개수 구하기
4+
// 우선순위큐 구현해서 하는 것이 베스트
5+
const solution = (N, road, K) => {
6+
const graph = Array.from({ length: N + 1 }, () => [])
7+
for (let [a, b, w] of road) {
8+
graph[a].push([b, w])
9+
graph[b].push([a, w])
10+
}
11+
12+
const distance = Array(N + 1).fill(Infinity)
13+
distance[1] = 0
14+
15+
const pq = [[0, 1]] // [거리, 노드]
16+
17+
while (pq.length > 0) {
18+
const [dist, cur] = pq.shift()
19+
20+
if (distance[cur] < dist) continue
21+
22+
for (const [next, w] of graph[cur]) {
23+
const cost = dist + w
24+
if (cost < distance[next]) {
25+
distance[next] = cost
26+
pq.push([cost, next])
27+
}
28+
}
29+
}
30+
31+
return distance.filter((dist) => dist <= K).length
32+
}

0 commit comments

Comments
 (0)