본문 바로가기

릿코드Leetcode

Union Find [파이썬] 547. Friend Circles 릿코드 leetcode [2]

 

leetcode.com/problems/friend-circles/

Union Find 문제

 

Friend Circles - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

유니온 파인드 개념: kakunblog.tistory.com/16


 

 

class Solution(object):
    def findCircleNum(self, M):
        sets = [i for i in range(len(M))]

        def find(x):
            if x == sets[x]:
                return x
            sets[x] = find(sets[x])
            return sets[x]

        for j in range(0, len(M)):
            for i in range(j+1, len(M)):
                if M[i][j] == 1:
                    sets[find(i)] = find(j)

        return sum([1 for i, v in enumerate(sets) if i == v])

 

 

다른 유니온 파인드 문제: kakunblog.tistory.com/19

 

릿코드 leetcode Union Find 파이썬 684. Redundant Connection

Union Find를 이용해서 풀기 유니온 파인드 개념: kakunblog.tistory.com/16 class Solution(object): def findRedundantConnection(self, edges): sets = [0] * (len(edges)+1) def find(x): if sets[x] == 0: r..

kakunblog.tistory.com