📅  最后修改于: 2023-12-03 15:12:36.277000             🧑  作者: Mango
本章主要涉及计算机科学领域中的图论算法。图论是计算机科学中重要的一个分支领域,它研究的是图和网络中的算法和结构。
图可以用邻接矩阵、邻接表等方式进行表示。邻接矩阵适用于稠密图,而邻接表适用于稀疏图。以下是一个基于邻接表表示的无向图的例子:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
图的遍历可以分为深度优先遍历(DFS)和广度优先遍历(BFS)。以下是一个基于DFS的遍历实现的代码片段:
def dfs(graph, v, visited):
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
最短路径算法有多种实现,其中比较常用的是Dijkstra算法和Bellman-Ford算法。以下是一个基于Dijkstra算法的实现代码片段:
def dijkstra(graph, src):
dist = {i: float('inf') for i in graph}
dist[src] = 0
visited = [False] * len(graph)
for _ in range(len(graph)):
u = get_min_distance(dist, visited)
visited[u] = True
for v, weight in graph[u]:
if not visited[v]:
dist[v] = min(dist[v], dist[u] + weight)
return dist
def get_min_distance(dist, visited):
min_distance = float('inf')
min_index = -1
for i in range(len(dist)):
if not visited[i] and dist[i] < min_distance:
min_distance = dist[i]
min_index = i
return min_index
最小生成树算法有多种实现,其中比较常用的是Prim算法和Kruskal算法。以下是一个基于Prim算法的实现代码片段:
def prim(graph, vertices):
min_cost = 0
visited = [False] * len(graph)
key = [float('inf')] * len(graph)
key[0] = 0
for _ in range(len(graph)):
u = get_min_key(key, visited)
visited[u] = True
min_cost += key[u]
for v, weight in graph[u]:
if not visited[v] and weight < key[v]:
key[v] = weight
return min_cost
def get_min_key(key, visited):
min_key = float('inf')
min_index = -1
for i in range(len(key)):
if not visited[i] and key[i] < min_key:
min_key = key[i]
min_index = i
return min_index
以上是本章涉及的部分内容,图论算法在计算机科学中应用非常广泛,对于计算机科学专业的学生和从事相关工作的程序员,学习掌握这些算法是非常必要的。