Algorithm/noj.am

[Python] 백준 2606번 - 바이러스

SweetDev 2021. 1. 25. 09:12
# 2606 바이러스
import sys

nodes = int(sys.stdin.readline())
pairs = int(sys.stdin.readline())
node_set = set()
adjacencyList = [[] for _ in range(nodes+1)]
visitedList = []
for _ in range(pairs):
    a, b = map(int, sys.stdin.readline().split())
    if a not in node_set:
        node_set.add(a)
    if b not in node_set:
        node_set.add(b)
    if a not in adjacencyList[b]:
        adjacencyList[b].append(a)
    if b not in adjacencyList[a]:
        adjacencyList[a].append(b)

for i in adjacencyList:
    i.sort()
# print(adjacencyList)
stack = [1]

while stack:
    current = stack.pop()
    for neighbor in adjacencyList[current]:
        if not neighbor in visitedList:
            stack.append(neighbor)
    if current not in visitedList:
        visitedList.append(current)

# print(visitedList)
print(len(visitedList)-1) # 1은 제외