python 的图搜索
时间: 2023-10-18 18:30:45 浏览: 32
图搜索是一种用于在图数据结构中寻找特定节点或路径的算法。Python中有多种图搜索算法的实现,其中最常见的包括深度优先搜索(DFS)和广度优先搜索(BFS)。以下是一个简单的示例代码,演示如何使用DFS和BFS在图中进行搜索:
```python
# 使用邻接表表示图
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
# 深度优先搜索
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)
# 广度优先搜索
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[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# 测试DFS和BFS
print("DFS:")
dfs(graph, 'A', set())
print("\nBFS:")
bfs(graph, 'A')
```
这是一个简单的例子,图的表示方式使用了邻接表。你可以根据自己的需求来调整代码以适应不同的图结构。