邻接矩阵非递归深度遍历和邻接链表非递归层次遍历
时间: 2023-12-10 14:04:03 浏览: 82
c++实现图的邻接表深度优先遍历,广度优先遍历
以下是邻接矩阵非递归深度遍历和邻接链表非递归层次遍历的Python实现:
邻接矩阵非递归深度遍历:
```python
def DFS_iterative(graph, start):
visited = set() # 用集合存储已访问的节点
stack = [start] # 用栈存储待访问的节点
while stack:
vertex = stack.pop() # 取出栈顶节点
if vertex not in visited:
visited.add(vertex) # 将节点标记为已访问
print(vertex, end=' ')
# 将该节点的未访问过的邻居节点入栈
stack.extend([v for v in range(len(graph[vertex])) if graph[vertex][v] and v not in visited])
# 示例
graph = [[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]]
DFS_iterative(graph, 0) # 从节点0开始深度遍历
```
输出结果为:0 2 3 1
邻接链表非递归层次遍历:
```python
from collections import deque
def BFS_iterative(graph, start):
visited = set() # 用集合存储已访问的节点
queue = deque([start]) # 用队列存储待访问的节点
while queue:
vertex = queue.popleft() # 取出队首节点
if vertex not in visited:
visited.add(vertex) # 将节点标记为已访问
print(vertex, end=' ')
# 将该节点的未访问过的邻居节点入队
queue.extend([v for v in graph[vertex] if v not in visited])
# 示例
graph = {0: [1, 2],
1: [0, 3],
2: [0, 3],
3: [1, 2]}
BFS_iterative(graph, 0) # 从节点0开始层次遍历
```
输出结果为:0 1 2 3
阅读全文