728x90
https://www.acmicpc.net/problem/1260
from collections import deque
# dfs 함수
def dfs(graph, v, dfs_visited):
dfs_visited[v] = True
print(v, end=' ')
for i in graph[v]:
if not dfs_visited[i]:
dfs(graph, i, dfs_visited)
# bfs 함수
def bfs(graph, v, bfs_visited):
queue = deque([v])
bfs_visited[v] = True
while queue:
vv = queue.popleft()
print(vv, end=' ')
for i in graph[vv]:
if not bfs_visited[i]:
queue.append(i)
bfs_visited[i] = True
# 정점 개수, 간선 개수, 탐색 시작 정점 번호
n, m, v = map(int, input().split())
graph = [[] for i in range(n+1)]
for i in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
for i in graph:
i.sort()
dfs_visited = [False] * (n + 1)
bfs_visited = [False] * (n + 1)
dfs(graph, v, dfs_visited)
print()
bfs(graph, v, bfs_visited)
반응형
'전.py' 카테고리의 다른 글
[python] 미로 탈출 (0) | 2022.07.11 |
---|---|
[python] 음료수 얼려 먹기 (0) | 2022.07.11 |
[python] DFS & BFS (0) | 2022.07.08 |
[python] 팩토리얼 (0) | 2022.07.08 |
[python] 게임 개발 (0) | 2022.07.08 |