문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
제한사항
- 컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
- 각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
- i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
- computer[i][i]는 항상 1입니다.
입출력 예
n | computers | return |
3 | [[1, 1, 0], [1, 1, 0], [0, 0, 1]] | 2 |
3 | [[1, 1, 0], [1, 1, 1], [0, 1, 1]] | 1 |
입출력 예 설명
예제 #1
아래와 같이 2개의 네트워크가 있습니다.
예제 #2
아래와 같이 1개의 네트워크가 있습니다.
나의 코드
아래는 순서대로 역대 코드들인데 왜 코딩실력이 퇴화되는것같을까..?
from collections import deque
def solution(n,computers):
answer = 0
visited = [False for _ in range(n)]
for i in range(n):
if visited[i] == False:
visited[i]=True
queue = deque([i])
print(queue)
answer += 1
while queue:
idx = queue.popleft()
visited[idx]=True
for j in range(len(computers[idx])):
if visited[j] == False and computers[idx][j] == 1:
queue.append(j)
return answer
def solution(n, computers):
cnt=0
answer=0
visited=[0 for i in range(n)]
def dfs(i):
for j in range(n):
if computers[i][j] and not visited[j]:
visited[j]=1
dfs(j)
for i in range(n):
if not visited[i]:
visited[i]=1
dfs(i)
cnt+=1
answer=cnt
return answer
def solution(n, computers):
answer = 0
tree = {}
visit = [0 for i in range(n + 1)]
for i in range(n):
for nn, j in enumerate(computers[i]):
if j == 1 and nn == i or j == 0:
continue
elif i + 1 in tree:
tree[i + 1].append(nn + 1)
else:
tree[i + 1] = [nn + 1]
def bfs(i):
print(i)
visit[i] = 1
if i in tree:
dq = deque([i])
while dq:
x = dq.pop()
for j in tree[x]:
if visit[j] == 0:
dq.append(j)
visit[j] = 1
for i in range(1, n + 1):
if visit[i] == 0:
bfs(i)
answer += 1
return answer
'알고리즘 > 프로그래머스' 카테고리의 다른 글
프로그래머스-369게임 (0) | 2024.01.01 |
---|---|
프로그래머스-연속된 수의 합 (0) | 2024.01.01 |
프로그래머스-가위바위보-구현 (1) | 2024.01.01 |
프로그래스머스-최소 직사각형-python (0) | 2023.11.23 |
프로래그래스머스 모의고사-python (0) | 2023.11.23 |