본문 바로가기
Programming/Python

[백준] 2606 | 바이러스

by 왕밤빵도라에몽 2025. 4. 7.
728x90

기본 아이디어

  • 딕셔너리로 노드 연결 관계 정의해주기
  • bfs
from collections import deque

def solution(graph):
    queue = deque([1])
    visited = set()
    visited.add(1)

    while queue:
        root = queue.popleft()
        for neighbor in graph.get(root, []):
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

    return len(visited) - 1

if __name__ == "__main__":
    node = int(input())
    edge = int(input())
    graph = {}
    for _ in range(edge):
        a, b = map(int, input().split())
        if a not in graph:
            graph[a] = [b]
        else:
            graph[a].append(b)

        if b not in graph:
            graph[b] = [a]
        else:
            graph[b].append(a)

    print(solution(graph))
  • dfs보단 bfs가 더 자연스러우나 둘 다 상관없긴 함
728x90

'Programming > Python' 카테고리의 다른 글

[프로그래머스] 조이스틱  (0) 2025.04.08
[프로그래머스] 소수 찾기  (0) 2025.04.07
[프로그래머스] 게임 맵 최단거리  (0) 2025.04.07
[프로그래머스] 더 맵게  (0) 2025.04.02
[프로그래머스] 타겟 넘버  (0) 2025.04.02