针对您的问题,我认为BFS仍然适用。
使用BFS解决传统迷宫问题,从起点开始,您需要执行以下步骤:
1. Enqueue every point that is accessible (not a piece of wall, and not visited) and connected to the current point.
2. Dequeue current point and mark it as VISITED.
从上面可以看出,BFS不会让任何一个点被访问两次,因此避免了循环。
你的问题
对于你的问题,BFS仍然有效,但我们将略微改变“可访问”的定义:
首先,我将介绍“迷宫”矩阵的外观。
以下图像中的数字表示什么意思。
(假设对象的大小为1 * 2,并且在移动时,对象的左上角停留在每个点上)。
00: The point can't be accessed, neither the object is horizontal nor vertical.
10: The point can be accessed if the object is horizontal
01: The point can be accessed if the object is vertical
11: The point can be accessed if the object is either horizontal or vertical
你的图形可以转换成下面这样的矩阵:
![img1](https://istack.dev59.com/RWiyF.webp)
用00填充那些无法访问的点,你会得到
![enter image description here](https://istack.dev59.com/JFv5m.webp)
这更像是一个迷宫问题,但略有不同。
最后,让我们看看如何“访问”这些点:
connected
的定义类似于传统的迷宫问题。以下是一些示例:
---------
| 01| 10|
|---|---|
| 10| |
--------- (Not Connected from top-left to either top-right or bottom-left)
---------
| 11| 10|
|---|---|
| 01| |
--------- (Connected from top-left to both top-right and bottom-left)
---------
| 10| 10|
|---|---|
| 01| |
--------- (Connected from top-left to top-right, but not connected to bottom-left)
所以其余部分可能很简单。遵循传统的BFS方法,并创建一个二维数组来存储每个点的最短路径长度。出队以获取当前点,将当前点的
相邻
连接点添加到队列中,并将此点标记为VISITED,然后一切都与BFS相同。
在获得最短路径之后,重新运行您的程序,在当前点保持对象是垂直还是水平的状态,并在图像上模拟您的移动。仅在必要时添加转弯,您将获得添加转弯的结果。