Data structure

dfs, bfs

study ticket 2021. 12. 5. 16:27
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