graph = dict()
graph['A'] = ['B', 'C']
graph['B'] = ['A', 'D']
graph['C'] = ['A', 'G', 'H', 'I']
graph['D'] = ['B', 'E', 'F']
graph['E'] = ['D']
graph['F'] = ['D']
graph['G'] = ['C']
graph['H'] = ['C']
graph['I'] = ['C', 'J']
graph['J'] = ['I']
graph
def bfs(gragh, start_node):
visited = list()
need_visit = list()
need_visit.append(start_node)
while need_visit:
# 맨 앞의 데이터 pop (queue)
node = need_visit.pop(0)
if node not in visited:
visited.append(node)
need_visit.extend(graph[node])
return visited
bfs(graph, 'A')
def dfs(gragh, start_node):
visited = list()
need_visit = list()
need_visit.append(start_node)
while need_visit:
# 맨 끝의 데이터 pop (stack)
node = need_visit.pop()
if node not in visited:
visited.append(node)
need_visit.extend(graph[node])
return visited
dfs(graph, 'A')