对于你的问题,我认为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
您的图表可以转换为如下矩阵:
用00填写那些无法访问的点,你就会得到
这更像是一个迷宫问题,但有点不同.
最后,让我们看看如何“访问”这些点:
连接的定义类似于传统的迷宫问题.这里有些例子:
---------
| 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相同.
在获得最短路径后,重新运行程序,在当前点保持对象是垂直还是水平的状态,并模拟您在图像上的移动.仅在必要时添加转弯,您将在添加转弯时获得结果.