코딩 테스트/문제 풀기
[프로그래머스] 네트워크
hazel_
2021. 4. 9. 14:19
programmers.co.kr/learn/courses/30/lessons/43162
def solution(n,computers):
parent=[0]*n
for i in range(n):
parent[i]=i
def find_parent(x):
if parent[x]!=x:
parent[x]=find_parent(parent[x])
return parent[x]
def union_parent(a, b):
a = find_parent(a)
b = find_parent(b)
if a < b:
if parent.count(b)>1:
while b in parent:
parent[parent.index(b)]=a
parent[b] = a
else:
if parent.count(a)>1:
while a in parent:
parent[parent.index(a)]=b
parent[a] = b
conn=[]
for i in range(n):
for j in range(n):
if computers[i][j]==1 and not i==j:
conn.append((i,j))
for a,b in conn:
if find_parent(a) != find_parent(b):
union_parent(a,b)
result=[0]*n
for i in range(len(parent)):
result[parent[i]]=1
answer=result.count(1)
return answer