Algorithm/Baekjoon

2606번 파이썬

@Eeap 2022. 3. 16. 22:24
반응형

저번에 풀었던 bfs 방법을 참고해서 풀음!

import sys
input = sys.stdin.readline
from collections import deque
v=int(input())
e=int(input())
graph={}
for _ in range(e):
    n1,n2=map(int,input().split())
    if n1 not in graph:
        graph[n1]=[n2]
    elif n2 not in graph[n1]:
        graph[n1].append(n2)
    if n2 not in graph:
        graph[n2]=[n1]
    elif n1 not in graph[n2]:
        graph[n2].append(n1)
queue=deque([1])
visited=[]
cnt=0
while queue:
    num = queue.popleft()
    if num not in visited:
        visited.append(num)
        cnt+=1
        ary=list(set(graph[num])-set(visited))
        queue+=ary
    
print(cnt-1)
반응형