查找AxB网格中的转弯数

时间:2013-03-03 10:55:40

标签: c++ arrays grid

所以,基本上,请查看下图:

Image

这是一个4x5的网格解释,但实际的挑战要求您输入网格尺寸。所以,我的工作是编写一个程序来计算你的转弯量(在这种情况下是红点)。起始位置始终位于左下角。那家伙正在按时钟的箭头移动(“右”)。

程序输入/输出是: 您输入网格尺寸: 4 5(例如)

输出方向变化量。 7

所以,我完全不知道它是如何完成的。我见过的解决方案如下:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    long long n, i,pom,m;
    int k,br=0;

    cin>>n>>m;
    if(n>m) {
        int pom=n;
        n=m;
        m=n;
    }
    if(n+1>=m)
        cout<<(n-1)+(m-1);
    else
        cout<<(n-1) +(n-1)+1;

    return 0;
}

但是我不明白以下的例子......谁能解释一下会发生什么?或者任何其他解决这个问题的方法总是受欢迎的。

3 个答案:

答案 0 :(得分:2)

int res = 0;
if(height == width)
    res = height * 2 - 2;//when height is odd than you will have 2 rows with single red dot
                           //when height is even you will have one row without red dot (all the rest have 2 red dots.
else if (width > height)
   res = height * 2 - 1;//one rows with 1 red dot the rest with 2 red dots.
else //height > width
   res = width * 2 - 2// 2 columns with one red dot and the rest with 2 red dots.

答案 1 :(得分:1)

我不是C ++人,所以无法理解代码。但肯定有助于了解这里的情况。 情况是转数仅取决于两个维度中的一个。哪个更少。因此,匝数取决于该侧的较小尺寸和箱数。因为在拍摄4X5阵列时,无论您将宽度增加到多少都是如此。只要高度为4,匝数将仅为7。 但是如果将宽度从4减小到3,则匝数现在取决于宽度。

现在关于点的数量。如果两个尺寸相同且为奇数,则假设尺寸为2A + 1,那么匝数将为4 * A.

如果一个尺寸较小,那么如果尺寸相同且均匀,则假设尺寸为2 * A,那么匝数将为4A-2。

如果较小的尺寸是偶数,则假设尺寸为2 * A,则转数将为4A-1。

如果较小的尺寸为奇数,则假设尺寸为2A + 1,则转数将为4A + 1.

看看这是否适用于您自己的新代码。

答案 2 :(得分:1)

此代码有条件地交换nm以生成n <= m

if(n>m) {
    int pom=n;
    n=m;
    m=n;
}

鉴于此,条件n+1>=m等同于n == m || n + 1 == m

请注意,公式(n-1)+(m-1)(n-1) +(n-1)+1都会为n + 1 == m提供相同的结果。

所以没有必要检查n + 1 == m;只有特殊情况n == m才是重要的。如果是n == m,那么您可以使用公式(n-1)+(m-1)2 * n - 2。否则,请使用公式(n-1) +(n-1)+12 * n - 1

重写代码:

int calculate_number_of_turns(int m, int n)
{
    if (m == n)
        return 2 * n - 2;
    else
        return 2 * std::min(m, n) - 1;
}

编辑:

如果你想从头开始编写你的代码,而不事先知道数学,你可以先写一个递归函数。

如果n = 2,很容易看到答案是3(3回合)。如果m = 2,那么答案是2.否则(假设n > 2m > 2),计算涉及为不同的参数调用相同的函数。

int calculate_number_of_turns(int m, int n)
{
    if (n == 2)
        return 3;
    else if (m == 2)
        return 2;
    else
        return calculate_number_of_turns(???, ???);
}

想象一下,启动图片中的路径,然后在第二个转弯后立即停止。如果你将图片颠倒过来,就像你用1和高度减1一样。所以调用m - 1, n - 1的相同函数将计算剩下的回合数,另外到前两个回合。

int calculate_number_of_turns(int m, int n)
{
    if (n == 2)
        return 3;
    else if (m == 2)
        return 2;
    else
        return 2 + calculate_number_of_turns(m - 1, n - 1);
}

现在,将这个递归函数转换为任何更简单的形式并不太复杂(只计算函数调用自身的次数,直到终止条件成立)。