반응형
문제:
https://www.acmicpc.net/problem/1260
풀이:
from collections import deque
n, m, v = map(int, input().split())
array = [[] for _ in range(n+1)]
result_dfs = 0
result_bfs = 0
visited_dfs = [False] * (n + 1)
visited_bfs = [False] * (n + 1)
for i in range(m):
x, y = map(int, input().split())
array[x].append(y)
array[y].append(x)
for i in range(len(array)):
array[i].sort()
def dfs(array, v, visited_dfs):
visited_dfs[v] = True
print(v, end=' ')
for i in array[v]:
if not visited_dfs[i]:
dfs(array, i, visited_dfs)
def bfs(array, start, visited_bfs):
queue = deque([start])
visited_bfs[start] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for i in array[v]:
if not visited_bfs[i]:
queue.append(i)
visited_bfs[i] = True
dfs(array, v, visited_dfs)
print()
bfs(array, v, visited_bfs)
반응형
'Python 코딩테스트' 카테고리의 다른 글
정렬: 백준 18868 파이썬 (0) | 2021.08.23 |
---|---|
정렬: 백준 11004 파이썬 (0) | 2021.08.23 |
DFS/BFS: 백준 2606 파이썬 (0) | 2021.08.18 |
DFS/BFS: 백준 16173 파이썬 (0) | 2021.08.12 |
구현: 백준 1236 파이썬(Python) (0) | 2021.08.06 |