c# – 如何修改递归算法以找到最短路径?

前端之家收集整理的这篇文章主要介绍了c# – 如何修改递归算法以找到最短路径?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
https://vimeo.com/70999946

我实现了递归路径查找算法.该递归算法基于连接在一起的预先设定的节点而工作.每个节点有四个包含更多方向的指针:Top,Button,Left和Right.递归算法简单地遍历每个节点并逐个寻找这四个方向中的每一个以到达其最终目的地;举例说明,考虑以下7个节点:A,B,C,D,E,F,G,H.

@H_403_4@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)

进入整体视图时,这些节点将显示下图.

@H_403_4@A—B—C | D—E—F | G—H

在此示例中,假设walker已启动节点为节点A,并且希望将节点H作为其最终目标.节点A按顺序查看自己的Right,Left和Top;它的右边指向节点B,因此他选择去节点B;相同模式的节点B选择向右移动,节点C.当步行者到达节点C时;当它的右边,顶部和按钮被阻塞时,节点C恢复到节点B.同样,节点B恢复节点A.步行器再次返回起始点.然后节点A根据订单转到其按钮节点;这意味着它进入节点D.节点D进入其右侧节点E,然后进入节点F.节点F被阻止;它返回到节点E和节点D.然后,节点D根据步行器顺序选择其按钮,节点G.从那里节点G进入节点H.最后,步行者到达其最终目的地.

@H_403_4@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,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,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,tempArrayList); 6.3- If tempArrayList is not null return tempArrayList 7-Return null; //*** End Condition does not found target }

注意:实际代码是C#,您可以从link下载.

案例研究中问题的出现:
当你理解这段代码时;它有一个弱点,以说明它;考虑以下节点的整体视图,假设起始节点是节点A,最终目的地是节点H.

@H_403_4@A—B—C | D—E—F—I | | | G—H—J—K

虽然最佳路径解是(A,H),但解释的递归路径寻找算法找到(A,I,K,J,H)作为其解;这真的看起来机器人是一个愚蠢的机器人:D!

图1:递归路径查找算法

图2:具有学习能力的递归路径查找算法

我通过添加节点的学习能力来解决问题.您可以从link中看到问题的详细信息.但是,我想知道是否有人可以修改递归算法以找到最短路径.

谢谢,

解决方法

你正在做 depth-first search,你想要做的是 breadth-first search.后者需要 queue而不是递归.维基页面很好地解释了如何实现它,所以我在此不再重复.

从那里开始,实施A*并没有多大工作,这应该可以加快你的结果.这将需要优先级队列而不是队列; C#在基本库中没有优先级队列,但幸运的是,我是专门用于寻路的optimized C# priority-queue implementation的作者.

此外,既然你提到了Unity,我会指出有专门为Unity构建的a number of pathfinding libraries.这可能是最安全的路线,因为视频游戏中的有效寻路是非常重要的.

原文链接:https://www.f2er.com/csharp/239166.html

猜你在找的C#相关文章