用邻接表和邻接矩阵两种结构,分别实现图的深度优先遍历和广度优先遍历
时间: 2024-06-13 22:06:12 浏览: 253
以下是使用邻接矩阵和邻接表两种结构实现图的深度优先遍历和广度优先遍历的方法:
使用邻接矩阵实现图的深度优先遍历:
```python
# 定义一个函数来实现深度优先遍历
def DFS(graph, start):
visited = set() # 用集合来存储已经访问过的节点
stack = [start] # 用栈来存储待访问的节点
while stack:
node = stack.pop() # 取出栈顶元素
if node not in visited:
visited.add(node) # 将节点标记为已访问
print(node, end=' ')
for i in range(len(graph)):
if graph[node][i] == 1 and i not in visited:
stack.append(i) # 将未访问的邻居节点入栈
# 定义一个邻接矩阵
graph = [[0, 1, 1, 0, 0],
[1, 0, 0, 1, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0]]
# 调用DFS函数进行深度优先遍历
DFS(graph, 0)
```
使用邻接矩阵实现图的广度优先遍历:
```python
# 定义一个函数来实现广度优先遍历
def BFS(graph, start):
visited = set() # 用集合来存储已经访问过的节点
queue = [start] # 用队列来存储待访问的节点
while queue:
node = queue.pop(0) # 取出队首元素
if node not in visited:
visited.add(node) # 将节点标记为已访问
print(node, end=' ')
for i in range(len(graph)):
if graph[node][i] == 1 and i not in visited:
queue.append(i) # 将未访问的邻居节点入队
# 定义一个邻接矩阵
graph = [[0, 1, 1, 0, 0],
[1, 0, 0, 1, 1],
[1, 0, 0, 1, 0],
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0]]
# 调用BFS函数进行广度优先遍历
BFS(graph, 0)
```
使用邻接表实现图的深度优先遍历:
```python
# 定义一个函数来实现深度优先遍历
def DFS(graph, start, visited):
visited.add(start) # 将节点标记为已访问
print(start, end=' ')
for neighbor in graph[start]:
if neighbor not in visited:
DFS(graph, neighbor, visited)
# 定义一个邻接表
graph = {0: [1, 2],
1: [0, 3, 4],
2: [0, 3],
3: [1, 2, 4],
4: [1, 3]}
# 调用DFS函数进行深度优先遍历
visited = set()
DFS(graph, 0, visited)
```
使用邻接表实现图的广度优先遍历:
```python
# 定义一个函数来实现广度优先遍历
def BFS(graph, start):
visited = set() # 用集合来存储已经访问过的节点
queue = [start] # 用队列来存储待访问的节点
visited.add(start) # 将节点标记为已访问
while queue:
node = queue.pop(0) # 取出队首元素
print(node, end=' ')
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor) # 将节点标记为已访问
queue.append(neighbor) # 将未访问的邻居节点入队
# 定义一个邻接表
graph = {0: [1, 2],
1: [0, 3, 4],
2: [0, 3],
3: [1, 2, 4],
4: [1, 3]}
# 调用BFS函数进行广度优先遍历
BFS(graph, 0)
```
阅读全文