编程实现: 1、 建立一个以邻接表或邻接矩阵形式存储的图; 2、 输出图的邻接表或邻接矩阵表示 3、进行图的深度优先遍历并打印遍历结果; 4、进行图的广度优先遍历并打印遍历结果; 5、退出系统。
时间: 2023-06-13 19:02:16 浏览: 158
以下是 Python 代码实现:
```python
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adj_list = {}
for vertex in vertices:
self.adj_list[vertex] = []
def add_edge(self, u, v):
self.adj_list[u].append(v)
self.adj_list[v].append(u)
def print_adj_list(self):
print("邻接表表示:")
for vertex in self.vertices:
print(vertex, "->", " -> ".join([str(adj_vertex) for adj_vertex in self.adj_list[vertex]]))
def print_adj_matrix(self):
print("邻接矩阵表示:")
adj_matrix = [[0 for _ in range(len(self.vertices))] for _ in range(len(self.vertices))]
for i, vertex in enumerate(self.vertices):
for adj_vertex in self.adj_list[vertex]:
j = self.vertices.index(adj_vertex)
adj_matrix[i][j] = 1
for row in adj_matrix:
print(row)
def dfs(self, start_vertex):
visited = set()
self._dfs(start_vertex, visited)
def _dfs(self, vertex, visited):
visited.add(vertex)
print(vertex, end=" ")
for adj_vertex in self.adj_list[vertex]:
if adj_vertex not in visited:
self._dfs(adj_vertex, visited)
def bfs(self, start_vertex):
visited = set()
queue = []
visited.add(start_vertex)
queue.append(start_vertex)
while queue:
vertex = queue.pop(0)
print(vertex, end=" ")
for adj_vertex in self.adj_list[vertex]:
if adj_vertex not in visited:
visited.add(adj_vertex)
queue.append(adj_vertex)
vertices = ["A", "B", "C", "D", "E", "F", "G"]
graph = Graph(vertices)
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("A", "D")
graph.add_edge("B", "E")
graph.add_edge("C", "F")
graph.add_edge("D", "G")
graph.print_adj_list()
graph.print_adj_matrix()
print("深度优先遍历:")
graph.dfs("A")
print()
print("广度优先遍历:")
graph.bfs("A")
print()
```
输出结果:
```
邻接表表示:
A -> B -> C -> D
B -> A -> E
C -> A -> F
D -> A -> G
E -> B
F -> C
G -> D
邻接矩阵表示:
[0, 1, 1, 1, 0, 0, 0]
[1, 0, 0, 0, 1, 0, 0]
[1, 0, 0, 0, 0, 1, 0]
[1, 0, 0, 0, 0, 0, 1]
[0, 1, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0]
深度优先遍历:
A B E C F D G
广度优先遍历:
A B C D E F G
```
阅读全文