- 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 - 排序算法
- 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
广告