路径规划——广度优先搜索与深度优先搜索
创作时间:
作者:
@小白创作中心
路径规划——广度优先搜索与深度优先搜索
引用
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寻找最短路径。
热门推荐
温室种植环境智能控制技术应用
汽车保险丝:你的爱车保命神器!
【渣翻·新生代之证#序言】奥特曼“现在”战斗的意义
西溪湿地旅游攻略:吃住行玩全攻略
城镇化进程中的拆迁难题:如何平衡各方利益?
合肥拆迁:城市蝶变的助推器
成皋之战:古代英雄争霸的经典战役
瓦兰迪亚势力起源 从游戏中看世界历史的变迁
天麻钩藤丸的功效与作用
圣尼古拉斯的秘密:圣诞袜里的爱与祝福
壁炉上的圣诞袜:传统与创意的完美融合
帝尧与鹿仙女的洞房花烛夜传说
圆明园十二生肖兽首:八尊已归国,四尊待寻觅
圆明园鼠首兔首回归特别纪念活动在国博举行
圆明园十二生肖兽首:八尊已归,四尊何在?
源自宫廷的长寿名方——五仙膏(暨五芝地仙金髓丹)
吐血是不是活不长了?一文读懂吐血原因与应对方法
突发呕血怎么办?这份急救指南请收好
嘴唇干裂脱皮唇炎怎么治疗
五分钟了解《德国国防军》1935至1945年间纳粹德国的军事力量称呼
揭秘乾隆帝的美食世界:从燕窝到烤鸭的皇家餐桌
国庆打卡故宫:太和殿&中和殿最美瞬间
太和殿:九五之尊的皇家威仪
故宫三大殿:皇权象征与文化瑰宝
自我接纳:克服自我否定的关键
恋爱中的自卑心理:如何克服这颗感情定时炸弹?
自我接纳:通往幸福的必经之路
职场中的创新思维与问题解决能力培养
古琴与传统文化
橘子价格暴跌背后:信息不对称与市场波动的双重影响