Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Recursion 递归地找到一条路径_Recursion_Path_Theory_Base - Fatal编程技术网

Recursion 递归地找到一条路径

Recursion 递归地找到一条路径,recursion,path,theory,base,Recursion,Path,Theory,Base,我有一系列从0到9的数字。每个数字代表一个具有x和y坐标的位置。所以,位置0可以表示(5,5)或类似的东西,总是(x,y)。现在我需要做的是使用5个位置递归地重击每个可能的路由,以获得用户给定的位置。例如: Input = (1, 2) //This is the co-ordinate the user gives. 现在给出这个输入,它应该选择所有可能的路径并找到最短的路径。有些路径可能是: start 0 1 2 3 4 input start 0 1 2 3 5 input start

我有一系列从0到9的数字。每个数字代表一个具有x和y坐标的位置。所以,位置0可以表示(5,5)或类似的东西,总是(x,y)。现在我需要做的是使用5个位置递归地重击每个可能的路由,以获得用户给定的位置。例如:

Input = (1, 2) //This is the co-ordinate the user gives.
现在给出这个输入,它应该选择所有可能的路径并找到最短的路径。有些路径可能是:

start 0 1 2 3 4 input
start 0 1 2 3 5 input
start 0 1 2 3 6 input
start 0 1 2 3 7 input
start 0 1 2 4 3 input
start 1 0 2 3 5 input
and so on....
它可以是0-9中5个数字的任意组合。它必须在输入目的地结束,在开始目的地开始。数字不能重复使用。因此,我需要递归地添加给定路线的所有距离(例如,开始0 1 2 3 4输入),并在通过这5个点时找到可能的最短路线


问:基本和递归情况是什么?

基本上,您要做的是从集合{1,…,n}生成大小k(路径长度)的所有组合,然后计算路径的值

下面是一个C代码示例:

void OPTPathForKSteps(List<int> currentPath, List<int> remainingPositions, int remainingSteps)
    {
        if (remainingSteps == 0)
        {
             // currentPath now contains a combination of k positions
             // do something with currentPath...
        }
        else
        {
            for (int i = 0; i < remainingPositions.Count; i++)
            {
                int TempPositionIndex = remainingPositions[i];
                currentPath.Add(TempPositionIndex);
                remainingPositions.RemoveAt(i);

                OPTPathForKSteps(currentPath, remainingPositions, remainingSteps - 1);

                remainingPositions.Insert(i, TempPositionIndex);
                currentPath.RemoveAt(currentPath.Count - 1);
            }
        }
    }
void OPTPathForKSteps(列出当前路径、列出剩余位置、整数剩余步骤)
{
如果(剩余步骤==0)
{
//currentPath现在包含k个位置的组合
//对currentPath执行某些操作。。。
}
其他的
{
for(int i=0;i
这是函数的初始调用(假设Positions是0…n个位置的整数列表,k是路径的长度):

OPTPathForKSteps(新列表(),位置,K);
您可以更改函数并添加参数,使其返回最佳路径和最小值。
还有其他(可能更短)的方法来创建这些组合,我的实现的好处是它的内存很轻,并且不需要存储所有可能的组合。

看看Dijkstra的算法
OPTPathForKSteps(new List<int>(), Positions, K);