2.设计一个基于图的邻接表的图的基本操作的演示程序。(234) 实现下列四种基本运算:(1)创建图;(2)深度优先遍历图;(3)广度优先遍历图;(4)转换图的存储结构()
时间: 2024-11-18 21:17:34 浏览: 26
设计一个简单的基于邻接表的图数据结构及其基本操作的Python示例:
```python
class Node:
def __init__(self, value):
self.value = value
self.neighbors = []
class Graph:
def __init__(self):
self.nodes = {}
# 创建图 - 添加顶点和边
def add_vertex(self, value):
if value not in self.nodes:
self.nodes[value] = Node(value)
def add_edge(self, src, dest):
if src in self.nodes and dest in self.nodes:
self.nodes[src].neighbors.append(dest)
self.nodes[dest].neighbors.append(src) # 如果图是非双向的,这一步可以省略
# 深度优先搜索 (DFS)
def dfs(self, start_node):
visited = set()
stack = [start_node]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
print(node.value, end=" -> ")
for neighbor in node.neighbors:
stack.append(neighbor)
# 广度优先搜索 (BFS)
def bfs(self, start_node):
visited = set()
queue = [start_node]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
print(node.value, end=" -> ")
for neighbor in node.neighbors:
queue.append(neighbor)
# 转换存储结构 - 将邻接列表转邻接矩阵 (仅适用于无向图)
def to_adjacency_matrix(self):
matrix = [[0] * len(self.nodes) for _ in range(len(self.nodes))]
for node, neighbors in self.nodes.items():
for neighbor in neighbors.neighbors:
matrix[node][neighbor] = 1
return matrix
# 示例
graph = Graph()
graph.add_vertex("A")
graph.add_vertex("B")
graph.add_vertex("C")
graph.add_vertex("D")
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("B", "C")
graph.add_edge("C", "D")
print("\nDepth First Search:")
graph.dfs(graph.nodes["A"])
print("\nBreadth First Search:")
graph.bfs(graph.nodes["A"])
print("\nAdjacency Matrix:")
matrix = graph.to_adjacency_matrix()
for row in matrix:
print(row)
```
这个程序首先定义了节点和图的数据结构,然后实现了添加顶点、添加边、深度优先搜索和广度优先搜索的操作,最后展示了如何将邻接表转换成邻接矩阵。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)