ALGORITHMS/BFS vs DFS

BFS vs DFS [adj. matrix]

로그앤 2022. 6. 19. 04:48

* USE DEQUE instead of queue 

# BFS vs DFS [adj matrix] # https://sexy-developer.tistory.com/54
#1. BFS -------------------------------------------------------------------------------------
def bfs(graph, start):
    visited = [False] * len(graph)
    answer = []
    queue = [start]
    visited[start] = True
    while queue:
        node = queue.pop(0)
        answer.append(node)
        for i in range(len(graph[node])):
            if graph[node][i] == 1 and not visited[i] and node != i:
                queue.append(i)
                visited[i] = True
        return answer

graph = [[1, 1, 1, 1, 0, 0],
         [1, 1, 0, 0, 0, 0],
         [1, 0, 1, 0, 0, 1],
         [1, 0, 0, 1, 1, 0],
         [0, 0, 0, 1, 1, 0],
         [0, 0, 1, 0, 0, 1]]
start = 0
#print("bfs 결과: ", bfs(graph, start))
#################################################################################################
#2. ITERATIVE DFS [adj. matrix] -------------------------------------------------------------------------------------
# 그래프를 반복적으로 dfs함
def iterative_dfs(graph, start):
    visited = [0] * len(graph)
    answer = []
    stack = [start]
    while stack:
        #print("\nstack: ", stack)
        temp = stack.pop()
        #print("pop된 노드: ", temp)
        visited[temp] = 1
        answer.append(temp)
        for i in range(len(graph[temp])):
            if graph[temp][i] == 1 and visited[i] == 0 and temp != i:
                stack.append(i)
    return answer
graph = [[1, 1, 1, 1, 0, 0],
         [1, 1, 0, 0, 0, 0],
         [1, 0, 1, 0, 0, 1],
         [1, 0, 0, 1, 1, 0],
         [0, 0, 0, 1, 1, 0],
         [0, 0, 1, 0, 0, 1]]
start = 0
print(iterative_dfs(graph,start))
########################################################################3
#3. RECURSIVE DFS [adj. matrix] -------------------------------------------------------------------------------------
def recursive_dfs(graph, start, visited, answer):
    visited[start] = 1
    answer.append(start)
    for i in range(len(graph[start])):
        if graph[start][i] == 1 and visited[i] == 0 and start != i:
            recursive_dfs(graph, i, visited, answer)
    return answer

graph = [[1, 1, 1, 1, 0, 0],
         [1, 1, 0, 0, 0, 0],
         [1, 0, 1, 0, 0, 1],
         [1, 0, 0, 1, 1, 0],
         [0, 0, 0, 1, 1, 0],
         [0, 0, 1, 0, 0, 1]]
start = 0
visited = [0] * len(graph)
print(recursive_dfs(graph,start,visited,answer=[]))