简体   繁体   English

用曼哈顿距离模式填充二维数组

[英]Filling a 2d array with manhattan distance pattern

I'm trying to do this homework for algorithms, they ask me to fill a two-dimensional array of int like this: 我正在尝试为算法做这项作业,他们要求我像这样填充一个二维数组:

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. 我用Java编写了代码,但是也可以使用其他任何语言……重要的是我认为的“公式”。 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. 因此,如果您可以帮助我解决该问题,那将很好,我尝试了在线查找代码,但是我什么也没找到……谢谢。

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);

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM