搜索算法python
时间: 2023-06-21 18:14:37 浏览: 66
Python 中常用的搜索算法包括深度优先搜索(DFS)、广度优先搜索(BFS)、A*算法等。以下是它们的 Python 实现示例:
1. 深度优先搜索(DFS):
```python
visited = set() # 记录已经访问过的节点
def dfs(node):
if node in visited:
# 如果已经访问过,直接返回
return
visited.add(node)
# 处理当前节点
for next_node in node.children():
dfs(next_node)
```
2. 广度优先搜索(BFS):
```python
from collections import deque
def bfs(start, end):
queue = deque([start])
visited = set([start])
while queue:
node = queue.popleft()
# 处理当前节点
if node == end:
return True
for next_node in node.children():
if next_node not in visited:
visited.add(next_node)
queue.append(next_node)
return False
```
3. A*算法:
```python
import heapq
def astar(start, end):
heap = [(0, start)]
visited = set([start])
while heap:
# 弹出最小代价的节点
cost, node = heapq.heappop(heap)
# 处理当前节点
if node == end:
return cost
for next_node in node.children():
if next_node not in visited:
visited.add(next_node)
# 计算代价,并加入堆中
next_cost = cost + node.cost(next_node)
heapq.heappush(heap, (next_cost, next_node))
return -1 # 无法到达终点
```
这里只是简单的示例,实际应用中需要根据具体问题进行调整。
阅读全文