我实现了一个递归路径查找算法。这个递归算法基于一组预设的相互连接的节点工作。每个节点都有四个指针,包含进一步的方向:上、下、左和右。递归算法简单地遍历每个节点,并依次寻找这四个方向中的每一个,以达到其最终目的地;例如,考虑以下7个节点:A、B、C、D、E、F、G、H。
A (Button->D, Right->B)
B (Right->C, Left->B)
C (Left->B)
D (Button->G, Right->E, Top->A)
E (Right->F, Left->D)
F (Left->E)
G (Right->H, Top->D)
H (Left->G)
这些节点在整体视图中将显示以下图像。
A—B—C
|
D—E—F
|
G—H
在这个例子中,假设行走者的起始节点是A节点,他的最终目的地是H节点。节点A按照顺序查看自己的右侧、下方、左侧和上方;由于它的右侧指向节点B,所以它选择前往节点B;节点B按照同样的模式选择其右侧的节点C。当行走者到达节点C时,由于它的右侧、上方和下方被阻挡,节点C回到了节点B。节点B也回到了节点A。行走者再次回到了起点。然后,节点A按照顺序前往其下方的节点D。节点D先前往其右侧的节点E,然后再前往节点F。由于节点F被阻挡,它返回到了节点E和节点D。之后,节点D按照行走者的顺序选择前往其下方的节点G。从那里,节点G前往节点H。最终,行走者到达了他的最终目的地。
Pseudocode: Recursive Path Finding Algorithm
ArrayList findPath(GameObject currentPoint , GameObject targetPoint , ArrayList InputArrayList)
{
1-Duplicate InputArrayList as tempArrayList
2-If the currentPoint equals to target Point return inputArrayList
//*** End Condition found target
3-If the Right side of the currentPoint is empty goto step 4
3.1- Add currentPoint to tempArrayList
//*** Call Right
3.2- tempArrayList = findPath(currentpoint.Right, targetPoint, tempArrayList);
3.3- If tempArrayList is not null return tempArrayList
4-If the Button side of the currentPoint is empty goto step 5
4.1- Add currentPoint to tempArrayList
//*** Call Button
4.2- tempArrayList = findPath(currentpoint.Button, targetPoint, tempArrayList);
4.3- If tempArrayList is not null return tempArrayList
5-If the Left side of the currentPoint is empty goto step 6
5.1- Add currentPoint to tempArrayList
//*** Call Left
5.2- tempArrayList = findPath(currentpoint.Left, targetPoint, tempArrayList);
5.3- If tempArrayList is not null return tempArrayList
6-If the Top side of the currentPoint is empty goto step 7
6.1- Add currentPoint to tempArrayList
//*** Call Top
6.2- tempArrayList = findPath(currentpoint.Top, targetPoint, tempArrayList);
6.3- If tempArrayList is not null return tempArrayList
7-Return null;
//*** End Condition does not found target
}
注意:实际代码是用C#编写的,您可以从此链接下载。
案例研究中出现的问题: 当您理解这段代码时,会发现它有一个弱点。为了说明这一点,请考虑以下节点的总体视图,假设起始节点是A节点,终点是H节点。
A—B—C
|
D—E—F—I
| | |
G—H—J—K
尽管最佳路径解决方案是(A,D,G,H),但解释递归路径查找算法将(A,D,E,F,I,K,J,H)作为其解决方案;这似乎表明机器人是一个愚蠢的机器人:D!
图1:递归路径查找算法
![enter image description here](https://istack.dev59.com/kgyTg.webp)
![enter image description here](https://istack.dev59.com/27pgT.webp)