-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path등대.py
More file actions
30 lines (25 loc) · 909 Bytes
/
등대.py
File metadata and controls
30 lines (25 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def solution(n, lighthouse):
from collections import defaultdict
import heapq
graph = defaultdict(list)
for a, b in lighthouse:
graph[a].append(b)
graph[b].append(a)
distances = [float('inf')] * (n + 1)
visited = [False] * (n + 1)
def dijkstra(start):
distances[start] = 0
heap = [(0, start)]
while heap:
dist, current = heapq.heappop(heap)
if visited[current]:
continue
visited[current] = True
for neighbor in graph[current]:
new_distance = dist + 1
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heapq.heappush(heap, (new_distance, neighbor))
dijkstra(1)
dijkstra(distances.index(max(distances)))
return max(distances)