白俊.1260番です.DFSとBFS Pythonプール


白俊.1260番です.DFSとBFS Pythonプール
質問リンクhttps://www.acmicpc.net/problem/1260

DFS&BFS : https://velog.io/@minan/DFSBFS-整列
import sys
input = sys.stdin.readline

# BFS를 위한 deque
from collections import deque

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

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

for _ in range(m):
    start, end = map(int, input().split())

    graph[start].append(end)
    graph[end].append(start)
    graph[start].sort()
    graph[end].sort()

visited = [False] * (n+1)

def dfs(graph, v, visited):
    visited[v] = True
    print(v, end=' ')
    # 현재 노드와 연결된 다른 노드를 재귀적으로 방문
    for i in graph[v]:
        if not visited[i]:
            dfs(graph, i, visited)

def bfs(graph, start, visited):
    queue = deque([start])

    visited[start] = True

    while queue:
        v = queue.popleft()
        print(v, end=' ')
        for i in graph[v]:
            if not visited[i]:
                queue.append(i)
                visited[i] = True

dfs(graph, v, visited)
print()
visited = [False] * (n+1)
bfs(graph, v, visited)