220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • brute-Force
  • 티스토리챌린지
  • 다익스트라
  • dfs
  • IMPLEMENT
  • Mathematics
  • 구현
  • 오블완
  • 프로그래머스
  • union-find
  • Lis
  • top-down
  • topological sort
  • Priority Queue
  • BFS
  • bitmasking
  • 위상 정렬
  • Dynamic Programming
  • REACT
  • binary search
  • disjoint set
  • implementation
  • Prefix Sum
  • Greedy
  • dp
  • simulation
  • Backtracking
  • Minimum Spanning Tree
  • two pointer
  • 백준

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/프로그래머스

[프로그래머스] 42861. 섬 연결하기

2022. 8. 7. 03:12

https://school.programmers.co.kr/learn/courses/30/lessons/42861

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

최소 신장 트리 (MST)의 Kruskal 알고리즘을 이용하여 풀었음.

 

우선 cost에 따라 오름차순으로 배열 정렬.

vertex의 연결을 저장하고, Union-Find에 이용할 dicionary를 하나 생성하고,

union-find를 구현(find, union func.)

 

Kruskal 알고리즘을 적용해

cost가 낮은 순으로 정렬한 edge들에 대해 순회하며

사이클이 생기지 않도록 간선(edge)를 연결.

(두 vertex를 연결할 때, root 노드가 동일하면 같은 set에 존재하는 것이므로 연결하게 되면 사이클이 된다.)

from collections import deque
def solution(n, costs):
    # sort by cost
    costs = sorted(costs, key=lambda x: x[2])
    costs = deque(costs)

    # vertex
    v = set([i[0] for i in costs])
    v2 = set([i[1] for i in costs])
    v.update(v2)

    # make union-find dictionary
    connect = {i: i for i in v}

    # feat union-find
    def find(x):
        if connect[x] == x:
            return x
        connect[x] = find(connect[x])
        return connect[x]

    def union(x, y):
        rx = find(x)
        ry = find(y)
        if rx < ry:
            connect[ry] = rx
        else:
            connect[rx] = ry

    answer = 0
    for v1, v2, cost in costs:
        # same root vertex = in same set.
        # so, find(v1) == find(v2) : cycle occur.
        if find(v1) != find(v2):
            union(v1, v2)
            answer += cost
            
    return answer

 

    'Algorithm/프로그래머스' 카테고리의 다른 글
    • [프로그래머스] 64061. 크레인 인형뽑기 게임
    • [프로그래머스] 42884. 단속카메라
    • [프로그래머스] 42862. 체육복
    • [프로그래머스] 43164. 여행경로
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바