네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
n-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개의 네트워크가 있습니다.
전형적인 DFS/BFS 문제이다. computers[0][0] 노드부터 시작하여 connect를 따라 순회하여 총 몇 개의 네트워크가 존재하는지 탐색하면 된다. n의 개수가 200개 이하로 작기 때문에 재귀를 이용하는 DFS로 풀어도 상관없고, 나는 재귀가 별로다! 라고 한다면 BFS로 풀어도 괜찮다. 그래서 코드도 두 가지 버전을 모두 작성해보기로 하였다.
def dfs(n, computers, start, visited):
visited[start] = True
for connect in range(n):
if connect != start and computers[start][connect] == 1:
if visited[connect] == False:
dfs(n, computers, connect, visited)
def bfs(n, computers, start, visited):
visited[start] = True
queue = [start]
while queue:
node = queue.pop(0)
visited[node] = True
for connect in range(n):
if connect != node and computers[node][connect] == 1:
if visited[connect] == False:
queue.append(connect)
def solution(n, computers):
answer = 0
visited = [False] * n
for start in range(n):
if visited[start] == False:
#dfs or bfs 택1
dfs(n, computers, start, visited)
bfs(n, computers, start, visited)
answer += 1
return answer