编程实现:输入图的邻接矩阵, 然后用 BFS遍历图。
时间: 2024-03-15 16:46:25 浏览: 54
好的,以下是 Python 代码实现:
```python
from queue import Queue
# 定义一个图类
class Graph:
def __init__(self, adjacency_matrix):
self.adjacency_matrix = adjacency_matrix
self.num_nodes = len(adjacency_matrix)
# BFS 遍历
def bfs(self, start_node):
visited = [False] * self.num_nodes
q = Queue()
q.put(start_node)
visited[start_node] = True
while not q.empty():
node = q.get()
print(node, end=" ")
for neighbor in range(self.num_nodes):
if self.adjacency_matrix[node][neighbor] == 1 and not visited[neighbor]:
q.put(neighbor)
visited[neighbor] = True
# 测试
if __name__ == '__main__':
# 示例邻接矩阵
adjacency_matrix = [[0, 1, 1, 0, 0],
[1, 0, 1, 1, 0],
[1, 1, 0, 1, 1],
[0, 1, 1, 0, 1],
[0, 0, 1, 1, 0]]
graph = Graph(adjacency_matrix)
graph.bfs(0) # 从节点 0 开始遍历
```
输出结果为:
```
0 1 2 3 4
```
阅读全文