반응형

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

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net

 

해결 방법 : BFS

  • 가장 기본적인 BFS 문제이다.
  • 특정 pc에 접근 되었는지만 판별하면 되므로, viruses Array를 두어 이미 접근한 pc는 이후에 무시하도록 한다.

 

import sys
input = sys.stdin.readline
from collections import defaultdict, deque

def solution(N, G):
    viruses = [0] * (N + 1) # 각 pc들의 virus 상태
    Q = deque([1]) # 1번 pc가 virus 걸림
    viruses[1] = 1

    while Q: # BFS
        cur_pc = Q.popleft() 
        for linked_pc in G[cur_pc]: # cur_pc와 link 된 pc들 중에서,
            if viruses[linked_pc] == 0: # 처음 접근하는 pc이면,
                viruses[linked_pc] = 1 # virus pc
                Q.append(linked_pc) # linked_pc 이후도 탐색

    return sum(viruses) - 1

if __name__ == '__main__':
    N = int(input())
    E = int(input())
    G = defaultdict(list)
    for _ in range(E):
        c1, c2 = map(int, input().split())
        G[c1].append(c2)
        G[c2].append(c1)
    result = solution(N, G)
    print(result)
반응형

'IT study > 알고리즘 문제 풀이' 카테고리의 다른 글

백준 7562 : 나이트의 이동  (0) 2021.08.09
백준 9204 : 체스  (0) 2021.08.07
백준 1138 : 한 줄로 서기  (0) 2021.08.05
백준 1058 : 친구  (0) 2021.08.03
백준 1005 : ACM Craft  (0) 2021.07.31

+ Recent posts