N, M, V = map(int, input().split())
matrix = [[0] * (N + 1) for _ in range(N+1)]
for _ in range(M):
link = list(map(int, input().split()))
matrix[link[0]][link[1]] = 1
matrix[link[1]][link[0]] = 1
def dfs(current_node, row, foot_prints):
foot_prints += [current_node]
for search_node in range(len(row[current_node])):
if row[current_node][search_node] and search_node not in foot_prints:
foot_prints = dfs(search_node, row, foot_prints)
return foot_prints
def bfs(start):
queue = [start]
foot_prints = [start]
while queue:
current_node = queue.pop(0)
for search_node in range(len(matrix[current_node])):
if matrix[current_node][search_node] and search_node not in foot_prints:
foot_prints += [search_node]
queue += [search_node]
return foot_prints
print(*dfs(V, matrix, []))
print(*bfs(V))
이번 코드는
https://this-programmer.com/entry/백준1260파이썬-DFS와-BFS
블로그를 참고하였습니다. 코드가 깔끔해서 보는사람 입장에선 이 코드를 포스팅하는게 낫다고 생각...
'# 코딩 문제 관련 > 파이썬' 카테고리의 다른 글
백준 11866번, 1158번(python) (0) | 2019.06.20 |
---|---|
백준 1966번(python) (0) | 2019.06.20 |
백준 10845번(python) (0) | 2019.06.17 |
백준 2504번(python) (0) | 2019.06.03 |
백준 9012번(python) (0) | 2019.06.02 |