from collections import deque
def bfs(graph,start_node):
queue=deque()
#조사할 노드 큐
visit=[]
#방문을 한 노드 리스트
queue.append(start_node)
#시작노드
while queue:
node=queue.popleft()
if node not in visit:
visit.append(node)
queue.extend(graph[node])
return visit
def dfs(graph,start_nod):
stack=deque()
visit=[]
stack.append(start_nod)
while stack:
node=stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
if __name__=="__main__":
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']
}
#그래프 구성
start_node='A'
#시작 노드
print(bfs(graph,root))
print(dfs(graph,root))
728x90
'Data structure' 카테고리의 다른 글
연결리스트로 Stack 구현하기 - c언어 (0) | 2022.03.14 |
---|---|
양방향 연결리스트(c언어) (0) | 2022.03.06 |
단방향 연결리스트(c언어) (0) | 2022.03.05 |
유클리드 호제법 (0) | 2021.12.02 |
에라토스의 체(python) (0) | 2021.12.02 |