图的邻接表创建、深度优先遍历和广度优先遍历代码实现,代码总汇
时间: 2023-06-21 15:09:26 浏览: 86
利用邻接表实现图的深度优先遍历
1. 图的邻接表创建
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj_list = [[] for i in range(vertices)]
def add_edge(self, u, v):
self.adj_list[u].append(v)
self.adj_list[v].append(u)
```
2. 深度优先遍历
```python
def dfs_helper(graph, node, visited):
visited.add(node)
print(node, end=" ")
for neighbor in graph.adj_list[node]:
if neighbor not in visited:
dfs_helper(graph, neighbor, visited)
def dfs(graph, start):
visited = set()
dfs_helper(graph, start, visited)
```
3. 广度优先遍历
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node, end=" ")
for neighbor in graph.adj_list[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
```
注意:以上代码仅为实现演示,可能存在一些细节问题,如实际应用中需要对图的节点编号进行处理等。
阅读全文