一、算法核心——基于广度优先搜索算法(BFS)
1.算法思想
首先访问起始顶点,接着由起始顶点v出发,依次访问v的各个未访问过的邻接顶点w1,w2,…,wn,然后依次访问w1,w2,…,wn的所有未被访问过的邻接顶点;再从这些访问过的顶点出发,访问它们所有未被访问过的邻接顶点,以此类推,直到图中所有顶点都被访问过为止。
2.具体实现步骤:
1.将网格阵列转化为一个可用数据结构(本文样例采用8x8网格)
2.表示可走区域:将 0视为可走区域,1视为不可走区域
3.初始化队列:从 a点开始,将其添加到队列中
4.探索相邻节点:检查上、下、左、右和斜对角八个方向的相邻点,如果是 0
且未被访问过,则将其加入队列
5.记录路径:可以用一个字典记录每个点的前驱节点,以便在找到 b时可以回溯路径
二、核心代码
图例:
# 定义方格阵列
grid = [
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 1, 1, 1, 1],
[0, 'a', 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 'b', 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0]
]
# 定义起点和终点
start = (3, 1) # a 的位置
end = (6, 5) # b 的位置
# 定义移动方向,包括对角方向
directions = [
(0, 1), (1, 0), (0, -1), (-1, 0), # 上下左右
(1, 1), (1, -1), (-1, 1), (-1, -1) # 对角线
]
def is_valid(x, y):
return 0 <= x < 8 and 0 <= y < 8 and (grid[x][y] == 0 or grid[x][y] == 'b')
def bfs(start, end):
queue = deque([start]) # 初始化队列
visited = set() # 用于存储已访问的节点
visited.add(start) # 将起点标记为已访问
parent = {start: None} # 记录每个节点的父节点
while queue:
current = queue.popleft() # 从队列中取出当前节点
if current == end:
# 找到目标节点,回溯路径
path = []
while current is not None:
path.append(current)
current = parent[current]
return path[::-1] # 反转路径
# 遍历所有可能的移动方向
for direction in directions:
neighbor = (current[0] + direction[0], current[1] + direction[1])
if is_valid(neighbor[0], neighbor[1]) and neighbor not in visited:
visited.add(neighbor) # 标记为已访问
queue.append(neighbor) # 加入队列
parent[neighbor] = current # 记录父节点
return None # 如果没有找到路径
path = bfs(start, end) # 查找路径
# 输出路径
if path:
print("从 a 到 b 的最短路径为:")
for step in path:
print(step)
else:
print("没有找到路径。")
三、运行结果