![](https://velog.velcdn.com/images%2Fguri_coding%2Fpost%2F17a44fa0-42d2-4817-bafb-6e8d71624ca8%2F%E1%84%8B%E1%85%A1%E1%86%AF%E1%84%80%E1%85%A9%E1%84%85%E1%85%B5%E1%84%8C%E1%85%B3%E1%86%B7%20%E1%84%85%E1%85%A9%E1%84%80%E1%85%A9.jpg)
문제 해석
- DFS와 BFS의 방문 순서를 저장하는 함수를 만들어보자.
- 정점의 개수 N, 간선의 개수 M, 시작할 정점의 번호 V
- 양방향 간선으로 연결된 두 정점의 번호가 나오게 됨
알고리즘 코드
- 기본적인 알고리즘이지만 출력하는 값이 dfs, bfs에서 pop해서 나오는 시점임을 기억해야 한다.
from collections import deque
N, M, V = map(int, input().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
visited = [0] * (N+1)
def dfs(graph, v):
print(v, end=' ')
visited[v] = 1
for i in sorted(graph[v]):
if visited[i] != 1:
dfs(graph, i)
dfs(graph, V)
print()
def bfs(graph, start):
queue = deque([start])
visited = []
visited.append(start)
while queue:
v = queue.popleft()
print(v, end=' ')
for i in sorted(graph[v]):
if i not in visited:
queue.append(i)
visited.append(i)
return visited
bfs(graph, V)