프로그래밍/알고리즘 공부
[알고리즘 공부] BFS vs DFS
코딩하는 문과생
2019. 11. 16. 19:03
BFS는 Breath First Search의 줄임말이다.
queue를 이용해 구현한다.
DFS는 Depth First Search의 줄임말이다.
Stack을 이용해 구현한다.
def bfs(graph, start_node):
visit = list()
queue = list()
queue.append(start_node)
while queue:
node = queue.pop(0)
if node not in visit:
visit.append(node)
queue.extend(graph[node])
return visit
def dfs(graph, start_node):
visit = list()
stack = list()
stack.append(start_node)
while stack:
node = stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
graph = {
'A': ['B'],
'B': ['A', 'C', 'H'],
'C': ['B', 'D'],
'D': ['C', 'E', 'G'],
'E': ['D', 'F'],
'F': ['E'],
'G': ['D'],
'H': ['B', 'I', 'J', 'M'],
'I': ['H'],
'J': ['H', 'K'],
'K': ['J', 'L'],
'L': ['K'],
'M': ['H']
}
print(bfs(graph, 'A'))
print(dfs(graph, 'A'))