progress

~/problems / Weighted graphs / Dijkstra (weighted shortest paths)

Walk to the nearest open pharmacy

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A town has intersections 0 .. n-1 joined by two-way streets (a, b, minutes). Tonight only the pharmacies at the intersections in open_at are open.

Implement nearest_pharmacy(n, streets, open_at) -> list[int]: element v is the shortest walk from v to any open pharmacy (0 if v has one), or -1 if none can be reached.

streets = [(0, 1, 4), (1, 2, 1), (2, 3, 6), (3, 4, 2), (1, 4, 10)]
nearest_pharmacy(6, streets, [0, 3])
# [0, 4, 5, 0, 2, -1]     node 2: via 1 to 0 is 5, direct to 3 is 6; node 5 is isolated
A town of six intersections with open pharmacies at 0 and 3; each intersection shows its walk to the nearest one, and intersection 2 is closer to 0 via 1 (5 minutes) than to 3 directly (6).
Badges: minutes to the nearest open pharmacy (green squares)

Up to 10^5 intersections and 2 * 10^5 streets. open_at may be empty or repeat an intersection.

⭐ Bonus: a speed test with 5,000 open pharmacies earns a star with one Dijkstra instead of one per pharmacy.

Show hint

put every pharmacy on the heap at distance 0 before you start; the first time a node is settled, its distance is to the nearest one.

Topic: Dijkstra (weighted shortest paths). Heap of (dist, node), skip stale entries; non-negative weights only.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc