https://www.acmicpc.net/problem/2606
import sys
input = sys.stdin.readline
from collections import deque
com_vertex = int(input().rstrip()) # 컴퓨터의 수
com_edge = int(input().rstrip()) # 연결된 쌍 개수
graph = [[] for i in range(com_vertex + 1)] # connect 저장 리스트 // 인덱스 0 은 사용 안함
visited = [0 for i in range(com_vertex + 1)] # 방문 여부 // 인덱스 0 은 사용 안함
cnt = 0
for i in range(com_edge):
# 연결된 컴퓨터의 정보가 언제가 1부터 등장한다는 보장 x
x, y = map(int, input().rstrip().split())
graph[x].append(y)
graph[y].append(x)
def bfs(start):
global cnt
visited[start] = True
q = deque([start])
while q:
now = q.popleft()
for i in graph[now]: # 방문한 컴퓨터와 연결된 컴퓨터 체크
if not visited[i]:
q.append(i) # 방문 예정인 컴퓨터를 q에 추가
visited[i] = True
cnt += 1
bfs(1) # 1번 컴퓨터를 통해 바이러스에 걸리게 됨.
print(cnt)
- 리스트에서 인덱스 0은 사용하지 않는다.
- 방문한 컴퓨터와 연결된 컴퓨터를 deq에 추가해 바이러스에 걸린 컴퓨터를 확인