图的邻接表存储及遍历
时间: 2024-04-30 16:14:10 浏览: 58
以下是关于图的邻接表存储及遍历的介绍:
1. 图的邻接表存储:
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.adj[u].append(v)
# 创建一个包含5个顶点的图
V = 5
graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
```
2. 图的邻接表遍历:
```python
class Graph:
# ... (同上)
def print_graph(self):
for v in range(self.V):
print("顶点", v, "的邻接表", end="")
for i in self.adj[v]:
print(" ->", i, end="")
print(" \n")
# 创建一个包含5个顶点的图
V = 5
graph = Graph(V)
# 添加边
# ... (同上)
# 打印邻接表
graph.print_graph()
```
阅读全文