Depth First Search (DFS): Searches from the root to the deepest node of the tree first
Breadth First Search (BFS): Searches the first depth of the nodes before moving on to the next depth
graph = {
# Root node is 1
# Nodes on the first level
1: [2, 5, 9],
# Node connected to 2
2: [1, 3],
# Node connected to 3
3: [2, 4],
4: [3],
5: [1, 6, 8],
6: [5, 7],
7: [6],
8: [5],
9: [1, 10],
10: [9]
}
visited = []
def dfs_recursion(adjacent_graph, cur_node, visited_array):
# 루트 노드부터 시작
visited_array.append(cur_node)
for adjacent_node in adjacent_graph[cur_node]:
# If the adjacent node is not visited
if adjacent_node not in visited_array:
dfs_recursion(adjacent_graph, adjacent_node, visited_array)
return visited_array
Stack is used as pop
returns the last node in an array that allows to search the depth first.
def dfs_stack(adjacent_graph, start_node):
visited = []
stack = [start_node]
# While stack is not empty
while stack:
# Put visited node in from stack to visited array
curNode = stack.pop()
visited.append(curNode)
# Check a node in stack
for adjNode in adjacent_graph[curNode]:
# If the adjacent node is not in the visited array
if adjNode not in visited:
# Append the adjacent node if not visited
stack.append(adjNode)
return visited
Queue is used as dequeue
returns the first node in an array that allows to evaluate the entire level first.
def bfs_queue(adj_graph, start_node):
visited = []
queue = [start_node]
# While queue is not empty
while queue:
# Dequeue visited node in from queue to visited array
curNode = queue[0]
queue.remove(curNode)
visited.append(curNode)
# Check a node in queue
for adjNode in adj_graph[curNode]:
# If the adjacent node is not in the visited array
if adjNode not in visited:
# Append the adjacent node if not visited
queue.append(adjNode)
return visited