数据结构与算法之——图的遍历-深度优先遍历和广度优先遍历-python实现
图的遍历-深度优先遍历和广度优先遍历-python实现
1、深度优先遍历
1.1 原理
暂时先不写,要画图很麻烦
1.2 python实现深度优先遍历

注:调用的栈类在这个文章:https://www.cnblogs.com/yechangxin/articles/16391518.html
# encoding=utf-8
from data_structures_and_algorithms.stock import Stack
"""
深度优先遍历 基于栈
"""
def DFS(graph, starting_point):
dfs_stock_obj = Stack() # 主栈
node_stock_obj = Stack() # 主栈节点的子节点栈对象
dfs_stock_obj.push(starting_point)
used_points_list = [] # 记录已经遍历过的点
used_points_list.append(starting_point)
while not dfs_stock_obj.is_empty_stock(): # 一直到所有子、根节点遍历完一次
_temp_top_value = dfs_stock_obj.pop() # 取出栈顶元素并删掉,即列表最后一个元素
node_stock_obj.stack_list = graph[_temp_top_value]
for j in range(node_stock_obj.size()): # 有几个子节点就遍历几次
i = node_stock_obj.get_top() # 取子节点栈顶,列表最后一位
if i not in used_points_list:
dfs_stock_obj.push(i)
used_points_list.append(i)
node_stock_obj.pop()
print(_temp_top_value)
if __name__ == '__main__':
graph = {
"0": ["1", "2", "3", "4"],
"1": ["0"],
"2": ["0", "9", "10"],
"3": ["0"],
"4": ["0", "5", "8"],
"5": ["4", "6", "7"],
"6": ["5"],
"7": ["5"],
"8": ["4"],
"9": ["2"],
"10": ["2"],
}
print("深度优先遍历:")
DFS(graph, '0')

2、广度优先遍历
2.1 原理
暂时先不写,要画图很麻烦
2.2 python实现广度优先遍历
from data_structures_and_algorithms.my_queue import Queue
"""
广度优先遍历
"""
def BFS(graph, starting_point): # 广度优先遍历,基于队列
bfs_queue_obj = Queue() # 主队列
node_queue_obj = Queue() # 主队列元素下的子队列
bfs_queue_obj.enqueue(starting_point)
used_points_list = [] # 记录已经遍历过的点
used_points_list.append(starting_point)
while not bfs_queue_obj.is_empty_queue(): # 一直到所有子、根节点遍历完一次
_temp_head_value = bfs_queue_obj.dequeue() # 队列先进先出
node_queue_obj.queue_list = graph[_temp_head_value]
for j in range(node_queue_obj.size()): # 有几个子节点就遍历几次
i = node_queue_obj.get_head() # 取子节点队头,列表第一位
if i not in used_points_list:
bfs_queue_obj.enqueue(i)
used_points_list.append(i)
node_queue_obj.dequeue()
print(_temp_head_value)
if __name__ == '__main__':
graph = {
"0": ["1", "2", "3", "4"],
"1": ["0"],
"2": ["0", "9", "10"],
"3": ["0"],
"4": ["0", "5", "8"],
"5": ["4", "6", "7"],
"6": ["5"],
"7": ["5"],
"8": ["4"],
"9": ["2"],
"10": ["2"],
}
print("广度优先遍历:")
BFS(graph, '0')

本文来自博客园,作者:JaxonYe,转载请注明原文链接:https://www.cnblogs.com/yechangxin/articles/16386516.html
侵权必究

浙公网安备 33010602011771号