본문 바로가기
Python/DFS&BFS

[Algorithm] 백준 2606 바이러스 | 파이썬 BFS

by 유일리 2024. 6. 26.

※ 2606 바이러스

https://www.acmicpc.net/problem/2606

문제 해결 TIP

너비우선 탐색 알고리즘인 BFS를 이용하여 쉽게 풀 수 있다. 1번 컴퓨터부터 큐에 삽입하여 주변 노드들을 방문 처리해준다.

 

전체 코드

from collections import deque

N = int(input())
M  = int(input())

graph = [[] for _ in range(N + 1)]

# 그래프 변환 작업
for _ in range(M):
    node1, node2 = map(int, input().split())
    graph[node1].append(node2)
    graph[node2].append(node1)

#graph = [[],[2, 5], [1, 3, 5], [2], [7], [1, 2, 6], [5], [4]]
virus = []

def bfs(graph,start,visited):
    queue = deque([start])
    visited[start] = True
    while queue:
        v = queue.popleft()
        virus.append(v)
        for i in graph[v]:
            if not visited[i]:
                queue.append(i)
                visited[i] = True
visited = [False]*(N+1)
bfs(graph,1,visited)
print(len(virus)-1)

댓글