Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

킹솔이

[백준/Python] 1260 DFS와 BFS 본문

Algorithm

[백준/Python] 1260 DFS와 BFS

킹솔이 2021. 1. 18. 22:15
import sys
from collections import deque

n, m, v = map(int, input().split())
graph = []

for i in range(n+1):
    graph.append([])

for i in range(m):
    x, y = map(int, sys.stdin.readline().split())
    graph[x].append(y)
    graph[y].append(x)

for i in range(n+1):
    graph[i].sort()

visited = [False for i in range(n+1)] 
def dfs(x):
    visited[x] = True
    print(x, end=" ")
    for i in graph[x]:
        if not visited[i]:
            dfs(i)

def bfs(x):
    que = deque()
    visited = [False for i in range(n+1)]
    visited[x] = True
    que.append(x)
    print(x, end=" ")
    while que:
        y = que.popleft()
        for i in graph[y]:
            if not visited[i]:
                que.append(i)
                visited[i] = True
                print(i, end=" ")

dfs(v)
print()
bfs(v)

기본 dfs와 bfs 문제이다.

정점 번호가 작은 순으로 방문하기 때문에 sort가 필요함.

'Algorithm' 카테고리의 다른 글

[백준/Python] 11497 통나무 건너뛰기  (0) 2021.01.18
[백준/Python] 5014 스타트링크  (0) 2021.01.17
[백준/Python] 2170 선 긋기  (0) 2021.01.15
[백준/Python] 13023 ABCDE  (0) 2021.01.13
[백준/Python] 14867 물통  (0) 2021.01.13