본문 바로가기
python

백준 DFS/ BFS 알고리즘 연습

by Gyona 2025. 6. 25.

바이러스- DFS

computer = int(input())
connect = int(input())

graph = [[] for _ in range(computer+1)] #컴퓨터와 연결된 컴퓨터 목록저장
visited = [False] * (computer +1) #0번자리 버리고 컴퓨터개수 +1개 자리만든후 방문했는지 안했는지 기록 남길것임

for _ in range(connect):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a) #양방향으로 연결해주기
    
def dfs(v): #v번 컴퓨터를 방문할것이다
    visited[v] = True
    for i in graph[v]:
        if not visited[i]:
            dfs(i)
dfs(1)            
    
print(visited.count(True)-1)

 

연결 요소의 개수 -DFS

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

n, e = map(int, input().split())

graph = [[]for _ in range (n+1)]
visited = [False] * (n+1)

#dfs함수
def dfs(v):
    visited[v] = True
    for i in graph[v]:
        if not visited[i]:
            dfs(i)
#숫자받아서 ab에 넣기
for _ in range(e):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)
#count 올리는 함수 작성
count = 0
for i in range(1, n+1):
    if not visited[i] :
        dfs(i)
        count +=1
#count출력
print(count)

그림 - BFS

from collections import deque

n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
visited = [[False] * m for _ in range(n)]

def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    visited[x][y] = True
    area = 1
    
    # 상하좌우 방향
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]
    
    while queue:
        x, y = queue.popleft()
        
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            
            if 0 <= nx < n and 0 <= ny < m:
                if not visited[nx][ny] and graph[nx][ny] == 1:
                    visited[nx][ny] = True
                    queue.append((nx, ny))
                    area += 1
                    
    return area

count = 0
max_area = 0

for i in range(n):
    for j in range(m):
        if graph[i][j] == 1 and not visited[i][j]:
            count += 1
            max_area = max(max_area, bfs(i, j))

print(count)
print(max_area)

'python' 카테고리의 다른 글

백준 이진탐색 알고리즘 연습  (0) 2025.06.27
백준 정렬 알고리즘 연습  (0) 2025.06.26
백준 재귀 함수 연습  (0) 2025.06.25
백준 - 스택,큐 알고리즘 연습  (0) 2025.06.25
백준 - 그리디  (0) 2025.06.24