DFS와 BFS 기초
from collections import deque
def DFS(graph, V):
visited = []
tempStack = [V]
while tempStack:
node = tempStack.pop()
if node not in visited:
visited.append(node)
tempStack.extend(sorted(graph[node], reverse=True))
return visited
def BFS(graph, V):
visited = []
queue = deque([V])
while queue:
node = queue.popleft()
if node not in visited:
visited.append(node)
queue.extend(sorted(graph[node]))
return visited
N, M, V = map(int, input().split())
graph = [set([]) for i in range(N + 1)]
for i in range(M):
a, b = map(int, input().split())
graph[a].add(b)
graph[b].add(a)
print(*DFS(graph, V))
print(*BFS(graph, V))
'Algorithm > BFS, DFS' 카테고리의 다른 글
[백준] 단어 공부 (0) | 2020.09.04 |
---|---|
[백준] 2675 문자열 반복 (0) | 2020.09.04 |
[백준] 2178번 미로 탐색 (0) | 2020.09.04 |
[프로그래머스] 정수 내림차순으로 배치하기 (0) | 2020.08.28 |
[프로그래머스] 문자열을 정수로 바꾸기 (0) | 2020.08.28 |
댓글