设计一个数据结构实验代码,要求:1. 熟练掌握图的两种存储方式:邻接矩阵和邻接表。 2. 通过领接表统计图中顶点度为n的顶点数量。 3. 通过邻接矩阵实现最小生成树的prime算法。
时间: 2023-05-30 21:06:11 浏览: 155
邻接矩阵实现最小生成树的prime算法代码:
```python
def prim(graph):
# 初始化
n = len(graph)
visited = [False] * n
dist = [float('inf')] * n
parent = [-1] * n
dist[0] = 0
# 选择n-1次最小边
for _ in range(n-1):
# 找到当前未访问的最小距离的点
u = min_distance(dist, visited)
visited[u] = True
# 更新与该点相邻的点的距离
for v in range(n):
if graph[u][v] and not visited[v] and graph[u][v] < dist[v]:
dist[v] = graph[u][v]
parent[v] = u
# 构建最小生成树
mst = []
for i in range(1, n):
mst.append((parent[i], i, graph[parent[i]][i]))
return mst
def min_distance(dist, visited):
min_dist = float('inf')
min_index = -1
for i in range(len(dist)):
if not visited[i] and dist[i] < min_dist:
min_dist = dist[i]
min_index = i
return min_index
```
邻接表统计图中顶点度为n的顶点数量的代码:
```python
def degree_count(adj_list, n):
count = 0
for i in range(len(adj_list)):
if len(adj_list[i]) == n:
count += 1
return count
```
阅读全文