图的广度优先遍历算法实现
时间: 2023-11-24 10:52:44 浏览: 72
以下是图的广度优先遍历算法实现的Python代码:
```python
from collections import deque
# 定义图类
class Graph:
def __init__(self, graph_dict=None):
if graph_dict is None:
graph_dict = {}
self.__graph_dict = graph_dict
# 添加节点
def add_node(self, node):
if node not in self.__graph_dict:
self.__graph_dict[node] = []
# 添加边
def add_edge(self, edge):
edge = set(edge)
(node1, node2) = tuple(edge)
if node1 in self.__graph_dict:
self.__graph_dict[node1].append(node2)
else:
self.__graph_dict[node1] = [node2]
# 广度优先遍历
def bfs(self, start_node):
visited = [start_node]
queue = deque([start_node])
while queue:
node = queue.popleft()
for neighbor in self.__graph_dict[node]:
if neighbor not in visited:
visited.append(neighbor)
queue.append(neighbor)
return visited
# 创建图实例
graph = Graph()
# 添加节点
graph.add_node('A')
graph.add_node('B')
graph.add_node('C')
graph.add_node('D')
graph.add_node('E')
# 添加边
graph.add_edge(('A', 'B'))
graph.add_edge(('B', 'C'))
graph.add_edge(('B', 'D'))
graph.add_edge(('D', 'E'))
# 广度优先遍历
print(graph.bfs('A')) # 输出:['A', 'B', 'C', 'D', 'E']
```
阅读全文