针对给定的无向图,实现图的深度优先遍历和广度优先遍历算法,并输出相应遍历的结果
时间: 2023-11-22 20:53:20 浏览: 96
假设给定的无向图用邻接表表示,下面是深度优先遍历和广度优先遍历算法的实现,并输出相应遍历的结果。
```python
# 定义图节点类
class GraphNode:
def __init__(self, val):
self.val = val
self.neighbors = []
# 深度优先遍历算法
def dfs(node, visited):
visited.add(node)
print(node.val)
for neighbor in node.neighbors:
if neighbor not in visited:
dfs(neighbor, visited)
# 广度优先遍历算法
def bfs(node):
visited = set()
queue = [node]
visited.add(node)
while queue:
curr = queue.pop(0)
print(curr.val)
for neighbor in curr.neighbors:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# 测试
# 构造无向图,邻接表表示如下:
# 1 -> 2 -> 4
# | ^
# v |
# 3 -> 5
node1 = GraphNode(1)
node2 = GraphNode(2)
node3 = GraphNode(3)
node4 = GraphNode(4)
node5 = GraphNode(5)
node1.neighbors = [node2, node3]
node2.neighbors = [node1, node4]
node3.neighbors = [node1, node5]
node4.neighbors = [node2]
node5.neighbors = [node3]
print("深度优先遍历结果:")
dfs(node1, set())
print("广度优先遍历结果:")
bfs(node1)
```
输出结果:
```
深度优先遍历结果:
1
2
4
3
5
广度优先遍历结果:
1
2
3
4
5
```
阅读全文