
- dfs 함수를 만들어 문제를 해결한다. 이때 deque를 이용한다.
- q를 돌리면서 인접한 노드를 찾은 뒤 발견하면 q에 저장하는 식으로 해결하는데, 이때 방문한 노드들은 visit에 저장한다.
- visit에 저장할 때 중복된 값이 저장될 수 있기 때문에 set을 통해 중복값을 없애주고, 1에서 감염된 컴퓨터의 개수만 구하므로 visit의 크기에서 1을 빼준다.
- 아래 코드는 살짝 정돈되지 않은 느낌이 있는데 큰 틀은 이렇다 란 식으로 참고만 하면 좋을 것같다.
- 메모리 : 32396 KB
- 시간 : 88 ms
import sys
from collections import deque
def dfs(start):
q = deque()
visit = []
q.append(start)
while q:
move = q.popleft()
visit.append(move)
for nd in node:
if move == nd[0] and nd[1] not in visit:
q.append(nd[1])
elif move == nd[1] and nd[0] not in visit:
q.append(nd[0])
visit = set(visit)
return len(visit)-1
n = int(input())
d = int(input())
node = []
for _ in range(d):
n1, n2 = tuple(map(int, sys.stdin.readline().split()))
pair = sorted([n1,n2])
node.append(pair)
print(dfs(1))