用曼哈顿距离模式填充2d阵列

时间:2021-01-23 21:37:51

I'm trying to do this homework for algorithms, they ask me to fill a two-dimensional array of int like this:

我正在尝试为算法做这个功课,他们让我填写这样的二维int数组:

4 3 2 3 4
3 2 1 2 3
2 1 0 1 2
3 2 1 2 3
4 3 2 3 4

I tried this in java:

我在java中试过这个:

int[][] array = new int[5][5];
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        array[i][j] = Math.abs(i - j);
    }
}

but it gives me something like this:

但它给了我这样的东西:

0 1 2 3 4
1 0 1 2 3
2 1 0 1 3
3 2 1 0 1
4 3 2 1 0

And it's not really the same thing, but it's the closest that I found. I wrote the code in java but it can be in any other language... the important is the "formula" I think. So if you can help me resolving this trouble it'll be nice, I tried to look for the code online but I didn't find anything... thank you.

它并不是一回事,但它是我发现的最接近的东西。我用java编写代码,但它可以使用任何其他语言......重要的是我认为的“公式”。所以,如果你能帮助我解决这个麻烦,那就太好了,我试着在网上寻找代码,但我没找到任何东西......谢谢。

2 个解决方案

#1


6  

It looks as if you're looking for the distance to the center. So you first have to calculate this point:

看起来好像在寻找到中心的距离。所以你首先必须计算这一点:

int center = array.length / 2; //assuming a quadratic array

Then, calculating the distance is quite easy:

然后,计算距离非常简单:

//for ...
array[i][j] = Math.abs(i - center) + Math.abs(j - center);

#2


-1  

This will also work.

这也有效。

int p=N-1;
for(i=0,l=N-1;i<=l;i++,l--)
{
    for(j=0,k=N-1;j<=k;j++,k--)
    {
        arr[i][j]=p;
        arr[i][k]=p;
        arr[l][j]=p;
        arr[l][k]=p;
        p--;
    }
    p=N-i-2;
}

#1


6  

It looks as if you're looking for the distance to the center. So you first have to calculate this point:

看起来好像在寻找到中心的距离。所以你首先必须计算这一点:

int center = array.length / 2; //assuming a quadratic array

Then, calculating the distance is quite easy:

然后,计算距离非常简单:

//for ...
array[i][j] = Math.abs(i - center) + Math.abs(j - center);

#2


-1  

This will also work.

这也有效。

int p=N-1;
for(i=0,l=N-1;i<=l;i++,l--)
{
    for(j=0,k=N-1;j<=k;j++,k--)
    {
        arr[i][j]=p;
        arr[i][k]=p;
        arr[l][j]=p;
        arr[l][k]=p;
        p--;
    }
    p=N-i-2;
}