네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
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 |
BFS 풀이
from collections import deque
def solution(n, computers):
answer = 0
visited = [False] * n
queue = deque()
for v in range(n):
if visited[v] is False: # 방문한 적이 없다면
queue.append(v) # 해당 컴퓨터 번호 입력
while queue: # 큐가 비어질때까지
current = queue.popleft() # 현재 확인중인 컴퓨터의 번호
visited[current] = True # 방문 처리
# 자기 자신이 아니고, 다른 컴퓨터와 관계가 1일 경우
for c in range(len(computers[current])):
if c != current and computers[current][c] == 1:
if visited[c] is False: # 방문하지 않은 컴퓨터라면
queue.append(c)
answer += 1 # 한 네트워크 탐색이 끝나면 answer 증가
# 방문한 적이 있다면
else:
continue
return answer
DFS 풀이
def dfs(current, n, computers, visited):
visited[current] = True # 현재 컴퓨터 방문 처리
for i in range(n):
if i != current and computers[current][i] == 1: # 연결된 컴퓨터라면
if visited[i] is False: # 아직 방문하지 않은 컴퓨터라면
dfs(i, n, computers, visited)
def solution(n, computers):
answer = 0
visited = [False] * n
for current in range(n):
if visited[current] is False:
dfs(current, n, computers, visited)
answer += 1 # dfs를 모두 수행하면 연결
return answer
[프로그래머스] 타겟 넘버 - 파이썬 / DFS, BFS (0) | 2021.12.30 |
---|---|
[프로그래머스] 다리를 지나는 트럭 - 파이썬(Python) / 스택, 큐 (0) | 2021.12.15 |
[프로그래머스] 기능 개발 - 파이썬(Python) / 스택/큐 (0) | 2021.12.15 |
[프로그래머스] 더 맵게 - 파이썬(Python)/힙 (0) | 2021.12.15 |
[Python] 문자열 압축 - 파이썬(Python) (0) | 2021.12.15 |