[Graph] 바이러스

박고은·2023년 5월 23일
0

알고리즘

목록 보기
8/12

from collections import deque

n = int(input())
m = int(input())
network = dict(zip(list(range(1, n+1)), [[] for i in range(n)]))

for i in range(m):
    a, b = map(int, input().split())
    network[a].append(b)
    network[b].append(a)

visited = []

def DFS(c):
    visited.append(c)
    for i in network[c]:
        if i not in visited: DFS(i)

DFS(1)
print(len(visited)-1)

연결된 네트워크 표현은 딕셔너리
1번 컴퓨터를 통해 감염되는 컴퓨터의 수를 구하는 문제 -> 모든 노드를 탐색하는 DFS를 활용
방문한 노드 배열에서 1번 컴퓨터를 제외한 개수를 출력

0개의 댓글