테스트 케이스는 통과했지만 채점을 통과하지 못함.
문제점1. deq안에 중복된 숫자가 들어감.
from collections import deque
def solution(n, computers):
answer = 0
net = 0
popnum = 0
com_cnt = [1 for i in range(n)]
deq = deque()
while 1 in com_cnt:
if com_cnt[popnum] == 1:
net = popnum
else:
net = com_cnt.index(1)
com_cnt[net] = 0
for j in range(0, n):
if computers[net][j] == 1 and com_cnt[j] == 1:
deq.append(j)
computers[net][j] = 0
if deq:
popnum = deq.popleft()
else:
answer += 1
return answer
❗해결: deq안에 넣을 때 중복체크를 해준 다음에 넣어줌.
n: 컴퓨터의 개수
computers: 연결에 대한 정보가 담긴 2차원 배열
answer: 네트워크 개수 세는 변수
net: 연결을 확인할 컴퓨터의 번호
popnum: deq에서 pop한 숫자
com_cnt: 연결을 확인한 컴퓨터를 확인해주는 배열(0:확인완료, 1:확인미완료)
deq: 확인하고 있는 컴퓨터와 연결된 컴퓨터의 번호를 담은 que
from collections import deque
def solution(n, computers):
answer = 0
net = 0
popnum = 0
com_cnt = [1 for i in range(n)]
deq = deque()
while 1 in com_cnt:
if com_cnt[popnum] == 1:
net = popnum
else:
net = com_cnt.index(1)
com_cnt[net] = 0
for j in range(0, n):
if computers[net][j] == 1 and com_cnt[j] == 1 and j not in deq:
deq.append(j)
if deq:
popnum = deq.popleft()
else:
answer += 1
return answer
내 코드는 메모리도 차지를 많이하고 코드도 길어서 코드가 짧은 다른 사람의 코드를 찾아보았음.
🔗풀이 참고
프로그래머스-네트워크 다른사람의 풀이를 참고하였습니다.
def solution(n, computers):
temp = []
for i in range(n):
temp.append(i)
for i in range(n):
for j in range(n):
if computers[i][j]:
for k in range(n):
if temp[k] == temp[i]:
temp[k] = temp[j]
return len(set(temp))
플로이드-워셜 알고리즘을 사용했다고함.
🔗프로그래머스 - 네트워크
https://programmers.co.kr/learn/courses/30/lessons/43162