일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 영어원서읽기
- 3줄정리
- 운동
- 파비최
- 읽기
- 링피트
- English
- FIT XR
- 영어공부
- 스탭퍼
- 괜찮음
- 쓰릴오브파이트
- 30분
- 월간
- 미드시청
- 뭐든
- Daily Challenge
- realclass
- Writing
- 리얼 클래스
- 사이드
- 프로젝트
- leetcode
- 만화도
- 10분
- 매일
- 화상영어
- 개발자
- 잡생각
- Problem Solving
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.09.15 Today's Challenge 본문
https://leetcode.com/problems/min-cost-to-connect-all-points/
Min Cost to Connect All Points - LeetCode
Can you solve this real interview question? Min Cost to Connect All Points - You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is
leetcode.com
크루스칼 알고리즘으로 푸는 문제
def m_dist(p1, p2):
return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
n = len(points)
visited = [False] * n
heap_dict = {0: 0}
min_heap = [(0, 0)]
mst_weight = 0
while min_heap:
w, u = heappop(min_heap)
if visited[u] or heap_dict.get(u, float('inf')) < w:
continue
visited[u] = True
mst_weight += w
for v in range(n):
if not visited[v]:
n_dist = m_dist(points[u], points[v])
if n_dist < heap_dict.get(v, float('inf')):
heap_dict[v] = n_dist
heappush(min_heap, (n_dist, v))
return mst_weight
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.09.17 Today's Challenge (0) | 2023.09.17 |
---|---|
2023.09.16 Today's Challenge (0) | 2023.09.16 |
2023.09.14 Today's Challenge (0) | 2023.09.14 |
2023.09.13 Today's Challenge (0) | 2023.09.13 |
2023.09.12 Today's Challenge (0) | 2023.09.12 |
Comments