对给定图,实现图的深度优先遍历和广度优先遍历。以邻接表或邻接矩阵为存储结构,实现连通无向图的深度优先和广度优先遍历。以用户指定的结点为起点,分别输出每种遍历下的结点访问序列,并调试算法。
时间: 2024-11-12 19:46:58 浏览: 9
无向图深度遍历邻接矩阵报告.doc
在图论中,深度优先遍历(Depth-First Search,DFS)和广度优先遍历(Breadth-First Search,BFS)是非常常见的两种搜索算法。以下是基于邻接表和邻接矩阵这两种常见数据结构的实现:
**邻接表存储结构:**
```python
class Graph:
def __init__(self):
self.vertices = {}
# DFS实现
def dfs(self, start_node):
visited = set()
stack = [start_node]
while stack:
node = stack.pop()
if node not in visited:
print(node, end=" -> ")
visited.add(node)
for neighbor in self.vertices[node]:
if neighbor not in visited:
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:
print(node, end=" -> ")
visited.add(node)
for neighbor in self.vertices[node]:
if neighbor not in visited:
queue.append(neighbor)
```
**邻接矩阵存储结构:**
```python
class AdjacencyMatrixGraph:
def __init__(self, num_vertices):
self.matrix = [[0] * num_vertices for _ in range(num_vertices)]
# DFS和BFS实现与邻接表版本类似,只是获取邻居的方式不同
def dfs_matrix(self, start_node):
# ... (同上,但通过索引来查找邻居)
def bfs_matrix(self, start_node):
# ... (同上,但通过索引来查找邻居)
```
为了调试算法,可以添加一些边界条件检查和异常处理,例如检查输入节点是否存在、循环检测等。运行遍历时,观察输出的结点访问序列是否符合预期,并记录每次遍历的时间性能。
阅读全文