반응형
SMALL
N, M, V = list(map(int, input().split()))
mat = [[] for _ in range(N + 1)]
for _ in range(M):
S, G = list(map(int, input().split()))
mat[S].append(G)
mat[G].append(S)
for _ in range(len(mat)):
mat[_] = sorted(mat[_])
# DFS
visited = [1 for _ in range(N + 1)]
DFS_result = []
def DFS(go):
visited[go] = 0
DFS_result.append(str(go))
for ch in range(len(mat[go])):
if visited[mat[go][ch]]:
DFS(mat[go][ch])
DFS(V)
# BFS
from collections import deque
visited = [1 for _ in range(N + 1)]
BFS_result = []
dq = deque()
dq.append(V)
visited[V] = 0
BFS_result.append(str(V))
while dq:
go = dq.popleft()
for ch in range(len(mat[go])):
if visited[mat[go][ch]]:
visited[mat[go][ch]] = 0
BFS_result.append(str(mat[go][ch]))
dq.append(mat[go][ch])
print(' '.join(DFS_result))
print(' '.join(BFS_result))
감을 찾기 위한 준비를 슬슬 합시다.
이상 DFS와 BFS - 1260번 였습니다. ^_^
반응형
LIST
'알고리즘 문제 풀이 > Baekjoon' 카테고리의 다른 글
10809 - 알파벳 찾기 (0) | 2019.08.11 |
---|---|
11720 - 숫자의 합 (C) (0) | 2019.08.11 |
미로 탐색 - 2178 (C++) (0) | 2019.06.28 |
팩토리얼 - 10872 (C) (0) | 2019.06.22 |
단지번호붙이기 - 2667번 (Python) (0) | 2019.06.21 |