路径规划——广度优先搜索与深度优先搜索
创作时间:
作者:
@小白创作中心
路径规划——广度优先搜索与深度优先搜索
引用
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寻找最短路径。
热门推荐
高血压患者必看:厄贝沙坦的正确使用指南
高换手率揭示股市新动向!
换手率飙升!你的投资策略该变了吗?
10个色彩心理的高级玩法
冬季护肝小贴士:正确使用恩替卡韦分散片
药品集采让恩替卡韦分散片价格大跳水!
恩替卡韦降价,乙肝患者的福音!
喀赞其老街:新疆多元文化的交融与新生
秋冬打卡:喀赞其民俗村的绝美风情
打卡喀赞其:感受西域风情的历史脉络
对色彩搭配感到困扰?学习平面设计中的绝妙色彩组合
浅蓝大衣如何选内搭?色彩搭配有妙招,让你的造型更出彩!
新疆国际大巴扎:文化传承与宗教和谐的典范
南宁冬日室内打卡胜地推荐:从主题乐园到文化展览,总有一款适合你
南宁冬至必吃暖身美食大揭秘!
北京康复医院专家推荐:艾灸改善手脚冰凉
朱棣把首都迁到北京是不是一招臭棋?
四位驻村干部的新年打算
驻村干部五大职责
德州旅游必打卡:黄河岛&古城墙&董子园
黄河国家地质公园:德州自驾游必打卡!
胃反酸缓解小妙招
消化不好要吃什么食物
胃酸倒流能吃和不能吃的食物。吃出舒适,避免胃酸倒流的秘密食谱!
人工智能在网络安全领域的应用与挑战
随时随地能睡着的他们,学习、婚姻、工作都被拖累
心理暗示的力量:积极心态如何改善生活与健康
有这4个表现的人,说明你的肾脏很健康
DASH饮食+新型药物:高血压治疗的新突破
中国医大专家详解:职场人群如何科学选择新型降压药?