※ 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)
'Python > DFS&BFS' 카테고리의 다른 글
[Algorithm] 백준 1012 유기농 배추 | 파이썬 BFS (0) | 2024.06.26 |
---|---|
[Algorithm] 백준 2667 단지번호붙이기 | 파이썬 DFS (0) | 2024.06.26 |
[Algorithm] 백준 14888 연산자 끼워 넣기 (삼성전자 SW 역량테스트 기출문제) | 파이썬 (0) | 2024.04.13 |
[Algorithm] 프로그래머스 타겟 넘버 | 파이썬 (0) | 2024.03.26 |
[Algorithm] 백준 1260 DFS와 BFS | 파이썬 (0) | 2024.01.17 |
댓글