0

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

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 个数字的任意组合。它必须在输入目的地结束并从起始目的地开始。号码不能重复使用。因此,我需要递归地添加给定路线的所有距离(例如 start 0 1 2 3 4 输入),并在通过这 5 个点时找到最短的路线。

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

4

1 回答 1

1

基本上你想要做的是从集合 {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);
            }
        }
    }

这是函数的初始调用(假设 Positions 是一个包含 0...n 个位置的整数列表,k 是路径的长度):

OPTPathForKSteps(new List<int>(), Positions, K);

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

于 2013-10-01T10:01:08.370 回答