python实现bfs dfs ucs
时间: 2023-11-04 18:03:08 浏览: 235
Python可以通过使用队列来实现广度优先搜索(BFS)、深度优先搜索(DFS),以及使用优先队列来实现统一代价搜索(UCS)。
BFS(广度优先搜索):
广度优先搜索是一种层次遍历的搜索算法,通过使用队列来实现。算法从根节点开始,将其加入到队列中,并将其标记为已访问。然后,从队列中取出第一个节点,并将其未访问的相邻节点加入到队列中,依此类推,直到队列为空。下面是一个Python示例代码:
```python
def bfs(graph, start):
visited = set()
queue = [start]
while queue:
node = queue.pop(0)
if node not in visited:
print(node)
visited.add(node)
neighbours = graph[node]
for neighbour in neighbours:
queue.append(neighbour)
# 调用方法
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
bfs(graph, 'A')
```
DFS(深度优先搜索):
深度优先搜索是一种通过递归实现的搜索算法,算法通过深入到最底层的节点,然后回溯到上一级节点继续搜索。下面是一个Python示例代码:
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_node in graph[start]:
if next_node not in visited:
dfs(graph, next_node, visited)
# 调用方法
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
dfs(graph, 'A')
```
UCS(统一代价搜索):
统一代价搜索是一种以路径的实际代价作为搜索优先级的算法,通过使用优先队列来实现。在搜索过程中,每个节点都被赋予一个代价,并且优先队列根据这些代价来选择节点。下面是一个Python示例代码:
```python
import heapq
def ucs(graph, start):
visited = set()
queue = [(0, start)]
while queue:
(cost, node) = heapq.heappop(queue)
if node not in visited:
print(node)
visited.add(node)
neighbours = graph[node]
for neighbour, neighbour_cost in neighbours:
if neighbour not in visited:
heapq.heappush(queue, (cost + neighbour_cost, neighbour))
# 调用方法
graph = {
'A': [('B', 2), ('C', 1)],
'B': [('D', 3), ('E', 2)],
'C': [('F', 4)],
'D': [],
'E': [('F', 1)],
'F': []
}
ucs(graph, 'A')
```
以上就是Python实现BFS、DFS和UCS的简单示例。
阅读全文