路径搜索问题:在给定的地图或图中,查找两个节点之间的最短路径或所有可能的路径。
我们分别使用广度优先搜索(BFS)和深度优先搜索(DFS)来解决路径搜索问题,即查找给定图中两个节点之间的最短路径或所有可能的路径。
首先,我们需要定义一个图的表示方法。在本例中,我们仍然使用邻接表来表示图。
广度优先搜索(BFS)方法:
from collections import defaultdict, deque
def bfs_shortest_paths(graph, start, target):
"""
使用广度优先搜索(BFS)找到图中从起始节点到目标节点的最短路径。
Parameters:
graph (dict): 图的邻接表表示。
start: 起始节点。
target: 目标节点。
Returns:
list: 最短路径的节点序列,如果不存在路径则返回空列表。
"""
queue = deque([(start, [start])]) # 使用队列存储节点及其路径
visited = set([start]) # 使用集合记录已经访问过的节点
while queue:
node, path = queue.popleft()
if node == target:
return path
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, path + [neighbor]))
return []
# 示例图的邻接表表示
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 搜索的起始节点和目标节点
start_node = 'A'
target_node = 'F'
# 找到最短路径
shortest_path = bfs_shortest_paths(graph, start_node, target_node)
if shortest_path:
print(f"最短路径从 {start_node} 到 {target_node} 是:", shortest_path)
else:
print(f"从 {start_node} 到 {target_node} 不存在路径")
深度优先搜索(DFS)方法:
def dfs_paths(graph, current, target, path=[], visited=set()):
"""
使用深度优先搜索(DFS)找到图中从起始节点到目标节点的所有可能路径。
Parameters:
graph (dict): 图的邻接表表示。
current: 当前遍历的节点。
target: 目标节点。
path (list): 当前路径。
visited (set): 已经访问过的节点集合,默认为空集合。
Returns:
list: 所有可能路径的列表。
"""
path = path + [current]
if current == target:
return [path]
if current not in graph:
return []
paths = []
visited.add(current)
for neighbor in graph[current]:
if neighbor not in visited:
new_paths = dfs_paths(graph, neighbor, target, path, visited)
for new_path in new_paths:
paths.append(new_path)
visited.remove(current)
return paths
# 示例图的邻接表表示
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 搜索的起始节点和目标节点
start_node = 'A'
target_node = 'F'
# 找到所有可能路径
all_paths = dfs_paths(graph, start_node, target_node)
if all_paths:
print(f"从 {start_node} 到 {target_node} 的所有可能路径是:", all_paths)
else:
print(f"从 {start_node} 到 {target_node} 不存在路径")
上述代码分别使用了广度优先搜索(BFS)和深度优先搜索(DFS)来查找从起始节点到目标节点的路径。其中,bfs_shortest_paths
函数使用广度优先搜索找到最短路径,而 dfs_paths
函数使用深度优先搜索找到所有可能的路径。