- Python 数据结构和算法教程
- Python-DS 主页
- Python-DS简介
- Python-DS 环境
- Python-数组
- Python - 列表
- Python - 元组
- Python-字典
- Python - 二维数组
- Python-矩阵
- Python - 集合
- Python - 地图
- Python - 链表
- Python-堆栈
- Python-队列
- Python-出队
- Python - 高级链表
- Python-哈希表
- Python - 二叉树
- Python - 搜索树
- Python - 堆
- Python - 图表
- Python - 算法设计
- Python——分而治之
- Python - 递归
- Python-回溯
- Python - 排序算法
- Python - 搜索算法
- Python - 图算法
- Python-算法分析
- Python - 大 O 表示法
- Python - 算法类
- Python - 摊销分析
- Python - 算法论证
- Python 数据结构和算法有用资源
- Python - 快速指南
- Python - 有用的资源
- Python - 讨论
Python - 图算法
图是解决许多重要数学挑战的非常有用的数据结构。例如计算机网络拓扑或分析化合物的分子结构。它们还用于城市交通或路线规划,甚至用于人类语言及其语法。所有这些应用程序都面临一个共同的挑战,即使用边遍历图并确保访问图的所有节点。有两种常见的既定方法可以进行这种遍历,如下所述。
深度优先遍历
也称为深度优先搜索 (DFS),该算法以深度方向运动遍历图,并在任何迭代中出现死端时使用堆栈来记住获取下一个顶点以开始搜索。我们使用设置的数据类型在 python 中实现图的 DFS,因为它们提供了跟踪已访问和未访问节点所需的功能。
例子
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
# Check for the visisted and unvisited nodes
def dfs(graph, start, visited = None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
dfs(gdict, 'a')
输出
执行上述代码时,会产生以下结果 -
a b d e c
广度优先遍历
也称为广度优先搜索(BFS),该算法遍历图的广度方向运动,并使用队列来记住在任何迭代中出现死胡同时获取下一个顶点以开始搜索。请访问我们网站中的此链接,了解图表的 BFS 步骤的详细信息。
我们使用前面讨论的队列数据结构在 python 中实现图的 BFS。当我们不断访问相邻的未访问节点并不断将其添加到队列中时。然后我们开始仅将没有未访问节点的节点出列。当没有下一个相邻节点要访问时,我们停止程序。
例子
import collections
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def bfs(graph, startnode):
# Track the visited and unvisited nodes using queue
seen, queue = set([startnode]), collections.deque([startnode])
while queue:
vertex = queue.popleft()
marked(vertex)
for node in graph[vertex]:
if node not in seen:
seen.add(node)
queue.append(node)
def marked(n):
print(n)
# The graph dictionary
gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
bfs(gdict, "a")
输出
执行上述代码时,会产生以下结果 -
a c b d e