Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- DP
- 그리디
- BOJ
- programmers
- 구현
- level2
- level3
- 백준
- 힙
- 브루트포스
- 스택
- 다익스트라
- BFS
- 운영체제
- 파이썬
- level0
- MYSQL
- 코딩테스트
- N과M
- 다이나믹 프로그래밍
- 가상메모리
- dict
- dfs
- 재귀
- 가상메모리 관리
- python
- level1
- 딕셔너리
- 수학
- 프로그래머스
Archives
- Today
- Total
동캄의 코딩도장
프로그래머스 level3 [섬 연결하기] 파이썬 본문
https://programmers.co.kr/learn/courses/30/lessons/42861
코딩테스트 연습 - 섬 연결하기
4 [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]] 4
programmers.co.kr
# 프로그래머스 섬 연결하기
def solution(n, costs):
answer = 0
costs.sort(key=lambda x: x[2])
island = {}
cnt = 0
for i in range(n):
island[i] = 0
a, b, c = costs.pop(0)
island[a] += 1
island[b] += 1
answer += c
cnt += 1
while cnt != n-1:
for i in range(len(costs)):
a, b, c = costs[i]
if island[a] >= 1 and island[b] >= 1:
continue
elif island[a] >= 1 and island[b] < 1:
island[a] += 1
island[b] += 1
answer += c
cnt += 1
costs.pop(i)
break
elif island[a] < 1 and island[b] >= 1:
island[a] += 1
island[b] += 1
answer += c
cnt += 1
costs.pop(i)
break
return answer
둘 다 연결된 적이 없는 섬이라면 --> 방문x
연결된 적이 있는 섬 과 연결되지 않은 섬이라면 --> 방문 o
둘 다 연결된 적 있는 섬 ---> 방문x
다음과 같은 방식으로 그리디하게 섬을 하나씩 확장해 나가면 된다.
'코테 > 프로그래머스' 카테고리의 다른 글
프로그래머스 level3 [가장 먼 노드] 파이썬 (0) | 2022.04.08 |
---|---|
프로그래머스 level3 [여행경로] 파이썬 (0) | 2022.04.08 |
프로그래머스 level3 [이중우선순위큐] 파이썬 (0) | 2022.04.07 |
프로그래머스 level3 [디스크 컨트롤] 파이썬 (0) | 2022.04.07 |
프로그래머스 level3 [베스트앨범] 파이썬 (0) | 2022.04.07 |