广度优先深度优先python 代码实现
时间: 2023-06-23 14:50:50 浏览: 116
好的,下面是Python实现广度优先搜索和深度优先搜索的示例代码:
广度优先搜索:
```python
from collections import deque
def bfs(graph, start, end):
queue = deque()
queue.append(start)
visited = set()
while queue:
node = queue.popleft()
if node == end:
return True
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
return False
```
深度优先搜索:
```python
def dfs(graph, start, end, visited=None):
if visited is None:
visited = set()
visited.add(start)
if start == end:
return True
for neighbor in graph[start]:
if neighbor not in visited:
if dfs(graph, neighbor, end, visited):
return True
return False
```
这里的`graph`是一个字典,表示图的邻接表,`start`是起点,`end`是终点。广度优先搜索使用了双端队列`deque`,深度优先搜索使用了递归。
阅读全文