본문 바로가기

ALGORITHMS/BFS vs DFS

BFS vs DFS [adj. list]

from collections import deque
#1. ADJACENCY MATRIX REPRESENTATION --> MUST SORT FIRST WHEN CONSTRUCTING GRAPH 2. USE DEFAULT DICT
#2. DFS --> STACK or RECURSION 
#3. BFS --> QUEUE (DEQUE) --> CANNOT USE RECURSION 
#4. APPEND (for adj in node[cur]) vs EXTEND (no looping required) 
graph1 = {
        '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']
    }
# 1A-1: BFS USING EXTEND
def BFS_EXTEND(graph,start):
    visited = []
    dq = deque(start)
    while dq:
        node = dq.popleft()
        if node not in visited:
            visited.append(node)
            dq.extend(graph[node])
    return visited


#1A-2: BFS USING APPEND
# 1. add start to vis before while loop 2. loop through each adj for graph[node]
def BFS_APPEND(graph,start):
    visited = [start]
    dq = deque(start)
    while dq:
        node = dq.popleft()
        for adj in graph[node]:
            if adj not in visited:
                visited.append(adj)
                dq.append(adj)
    return visited

#1B-1 DFS USING STACK ITERATION (EXTEND)
def DFS_EXTEND_ITERATIVE(graph,start):
    visited = []
    stack = [start]
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.append(node)
            stack.extend(graph[node])
    return visited

#1B-2 DFS USING STACK ITERATION (APPEND)
def DFS_APPEND_ITERATIVE(graph,start):
    visited = [start]
    stack = [start]
    while stack:
        node = stack.pop()
        for adj in graph[node]:
            if adj not in visited:
                visited.append(adj)
                stack.append(adj)
    return visited

#1B-3 DFS USING RECURSION (DOES NOT USE STACK)
def DFS_RECURSIVE(graph,start):
    vis.append(start)
    for node in graph[start]:
        if node not in vis:
            DFS_RECURSIVE(graph,node)
    return vis

print("BFS_EXTEND", BFS_EXTEND(graph1,"A"))
print("BFS_APPEND", BFS_APPEND(graph1,"A"))
print("DFS_EXTEND_ITERATIVE", DFS_EXTEND_ITERATIVE(graph1,"A"))
print("DFS_APPEND_ITERATIVE", DFS_APPEND_ITERATIVE(graph1,"A"))
vis = []
print("DFS_RECURSIVE", DFS_RECURSIVE(graph1,"A"))

'ALGORITHMS > BFS vs DFS' 카테고리의 다른 글

when to BFS vs DFS  (0) 2022.06.20
BFS vs DFS [adj. matrix]  (0) 2022.06.19