路径规划——广度优先搜索与深度优先搜索
创作时间:
作者:
@小白创作中心
路径规划——广度优先搜索与深度优先搜索
引用
CSDN
1.
https://blog.csdn.net/weixin_51995147/article/details/140859864
在图论中,广度优先搜索(BFS)和深度优先搜索(DFS)是最基本的两种图遍历算法。它们在很多领域都有广泛的应用,比如路径规划、网络爬虫、连通性检测等。本文将详细介绍这两种算法的原理、实现方法,并通过具体的代码示例帮助读者理解。
路径规划——广度优先搜索与深度优先搜索
1.广度优先搜索 Breath-First-Search
在图论中也称为广度优先遍历,类似于树的层序遍历。
算法原理
从起始节点出发,首先访问它的邻近节点,然后依次访问这些邻近节点的邻近节点,直到所有节点都被访问到。广度优先搜索是从一个起始节点开始逐层地访问所有节点的。
广度优先搜索是一种图遍历算法,每向前走一步可能访问一批顶点,不像深度优先搜索那样有回退的情况,因此它不是一个递归的算法。为了实现逐层的访问,算法必须借助一个辅助队列,以记忆正在访问的顶点的下一层顶点。
现有如下节点图Graph,要求从A点开始搜索,搜索全部节点,将节点搜索序列作为结果输出。
将上图整理得下图
那么整个广度优先搜索的过程如下图:
算法实现
from collections import deque
def bfs(graph, start):
# 初始化队列,并将起始节点加入队列
queue = deque([start])
# 初始化访问顺序列表
visited = [start]
while queue:
# 取出队列中的当前节点
current = queue.popleft()
# 遍历当前节点的所有邻居节点
for neighbor in graph[current]:
if neighbor not in visited: # 如果邻居节点尚未被访问
# 将邻居节点加入队列
queue.append(neighbor)
# 记录访问顺序
visited.append(neighbor)
return visited
# 示例图的定义
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 使用BFS算法
start_node = 'A'
visited = bfs(graph, start_node)
print(f"Visit order: {visited}")
寻找在上图中A->E的最短路径:
from collections import deque
def bfs(graph, start, goal):
# 初始化队列,并将起始节点加入队列
queue = deque([start])
# 初始化访问顺序列表
visited = [start]
# 初始化父节点集合
previous = {start: None}
while queue:
# 取出队列中的当前节点
current = queue.popleft()
if current == goal:
break
# 遍历当前节点的所有邻居节点
for neighbor in graph[current]:
if neighbor not in visited: # 如果邻居节点尚未被访问
# 将邻居节点加入队列
queue.append(neighbor)
# 记录访问顺序
visited.append(neighbor)
# 将当前节点保存为邻节点的父节点
previous[neighbor] = current
path = []
current = goal
# Find the full path by backtracking
while current is not None:
path.append(current)
current = previous.get(current)
path = path[::-1]
distance = len(path)-1
return path,distance
# 示例图的定义
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 使用BFS算法
start = 'A'
goal = 'E'
path,distance = bfs(graph, start, goal)
print("Distance: ",distance)
print(f"Short path: {path}")
输出结果:
利用BFS算法寻找栅格地图中两点之间的最短路径的代码实现如下:
from collections import deque
import numpy as np
class BFS:
def __init__(self, grid, board_size, start, goal):
self.grid = grid
self.board_size = board_size
self.start = start
self.goal = goal
def plan(self):
"""
Use BFS algorithm to plan path in grid map.
Since the cost between every two neighbouring nodes is 1 which is different from Dijkstra,
only four directions including up, right, down, left are allowed
"""
visited = set() # Used to mark nodes that are visited
self.searched = [] # Used to record nodes that are searched
previous_nodes = {self.start: None}
que = deque([self.start])
visited.add(self.start)
while que:
# Select the node closest to the start node
current_node = que.popleft()
# Append the current node into searched nodes
self.searched.append(current_node)
# Break when the current node is the goal
if current_node == self.goal:
break
# Find the neighbors of the current node and determine in turn if they have already been visited
neighbors = self.get_neighbors(current_node)
for neighbor in neighbors:
# If the current node has been visited, skip it
if neighbor in visited:
continue
previous_nodes[neighbor] = current_node
que.append(neighbor)
visited.add(neighbor) # mark the neighbor is visited
self.path = []
current_node = self.goal
# Find the full path by backtracking
while current_node is not None:
self.path.append(current_node)
current_node = previous_nodes.get(current_node)
self.path = self.path[::-1]
return len(self.path)-1
def get_neighbors(self, node):
neighbors = []
next_directions = [(1,0),(0,-1),(-1,0),(0,1)]
for next_d in next_directions:
neighbor = (node[0] + next_d[0], node[1] + next_d[1])
if self.board_size <= neighbor[0] < len(self.grid)-self.board_size and self.board_size <= neighbor[1] < len(self.grid[0])-self.board_size:
if self.grid[neighbor[0]][neighbor[1]] == 0:
neighbors.append(neighbor)
return neighbors
2.深度优先搜索 Depth-First-Search
在树和图论的数据结构中也称为深度优先遍历。
算法原理
从起始节点出发,沿着一个分支深入到尽可能深的节点,然后回溯并继续访问其他分支。这种"走到尽头再返回"的算法范式通常是基于递归来实现的。
同样以上述例子为例,整个深度优先搜索的过程如下:
算法实现
from collections import deque
def dfs(graph, current_node, visited):
visited.append(current_node)
# 遍历当前节点的所有邻居节点
for neighbor in graph[current_node]:
if neighbor in visited: # 如果邻居节点已被访问则跳过
continue
dfs(graph, neighbor, visited)
return visited
# 示例图的定义
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 使用DFS算法

start_node = 'A'
visited = dfs(graph, start_node, [])
print(f"Visit order: {visited}")
寻找在上图中A->E的最短路径:
from collections import deque
def dfs(graph, current_node, goal, path, shortest_path, distance):
path.append(current_node)
if current_node == goal:
if len(path)-1<distance:
shortest_path[:] = path
distance = len(shortest_path)-1
path.pop()
return shortest_path, distance
# 遍历当前节点的所有邻居节点
for neighbor in graph[current_node]:
if neighbor in path: # 如果邻居节点已被访问则跳过
continue
shortest_path, distance = dfs(graph, neighbor, goal, path, shortest_path, distance)
path.pop()
return shortest_path, distance
# 示例图的定义
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 使用DFS算法
start_node = 'A'
goal = 'F'
path = []
distance = float('inf')
shortest_path, distance = dfs(graph, start_node, goal, path, [], distance)
print("Distance: ",distance)
print(f"Short path: {shortest_path}")
输出结果:
虽然DFS可以找到最短路径,但是需要找到所有的路径之后才能知道最短路径,所有非常耗时,例如在上述BFS中的栅格地图中寻找起点到终点的最短路径是非常困难的,尽管也可以找到最短路径但是非常耗时,所以一般不会使用DFS寻找最短路径。
热门推荐
Qt多线程技术【线程池】:QRunnable 和 QThreadPool
AI生成声音也会侵权?这个案子判了!
中国电竞行业:面临挑战但期待涅槃重生
股票技术分析入门:从趋势到指标的全面解析
植物必需八大微量营养素关键生理功能与缺乏症状的关联
浇筑混凝土标号如何选择?全面解析不同标号的适用场景与施工要点
心狗团队研发世界首个“心电大模型”:面向全人群的自动心电图诊断系统
新闻媒体发稿的关键要点,策略、执行与优化
美媒评NBA史上最具统治力的10位球星:张伯伦第八,乔丹仅排第三
学霸们是如何高效率地学习、工作、生活的?
工人被困30米塔吊,高处作业安全知识全解析
四大名著改编,命运为何各不同?
装修施工时间几点到几点?合理安排装修时间,避免邻里纠纷
植物净化空气,让室内更健康(15种适合室内养护的净化空气植物推荐)
10 分钟+2 哑铃,站立式腹肌训练强核心!
悖论是那沙石砖瓦,智慧大厦不可缺
中国跳水队包揽8金!梦之队完美收官
深度探讨:有效沟通的艺术与技巧
跨学科选题的技巧与注意事项
应对强震施“妙策”——四川山区桥梁抗震技术发展及工程应用
JMeter压力测试工具使用详解
JMeter和JDK环境变量设置指南:Windows和Mac系统详细教程
工业4.0:企业数智化转型全面指南
毕加索:传奇一生,艺术之旅的无限魅力
基于多模态深度学习框架预测功能性磷酸化位点及其调控类型的方法MMFuncPhos
黄金标准法则:提升生活品质的必备指南
金融科技如何重塑银行业未来?
Excel 如何计算两个日期之间的天数、周数、月数或年数
月桂酸:一种重要的饱和脂肪酸
云南:暖意融融,彩云之南