GitHub

https://github.com/Choidongjun0830

파이썬 알고리즘 문제 풀이

[백준] 2606번 바이러스 DFS, BFS

gogi masidda 2024. 2. 21. 16:32

BFS

import sys
from collections import deque

input = sys.stdin.readline

N = int(input())
V = int(input())

graph = [[] for i in range(N+1)]
for i in range(V):
    a ,b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

visited = [0] * (N+1)

def bfs(V):
    count = 0
    queue = deque()
    queue.append(V)
    visited[V] = 1
    while queue:
        
        node = queue.popleft()
        for n in graph[node]:
            if visited[n] == 0:
                queue.append(n)
                visited[n] = 1
                count += 1
    return count

print(bfs(1))

 

DFS

import sys
sys.setrecursionlimit(10**6)

input = sys.stdin.readline
N = int(input())
V = int(input())

graph = [[] for i in range(N+1)]
for i in range(V):
    a ,b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

visited = [0] * (N+1)
count = 0
def dfs(V):
    global count
    visited[V] = 1
    for n in graph[V]:
        if visited[n] == 0:
            dfs(n)
            count += 1

dfs(1)
print(count)

 

DFS의 경우에는 count를 global 변수로 선언해야 사용가능하다.

728x90