2013-10-17 82 views
0

我知道如何遍历2D阵列的每个元素,使用array[i % n, i/n]时,对于n,m阵列,n = 0 < n * m。是否有一个方便的公式来遍历二维数组的边界元素?仅在其边界遍历2D或3D阵列/矩阵

例如,对于图2D中,给定的矩阵

enter image description here

'A' 被遍历。希望我能说明了3D,但希望这将清除它

+0

是否遍历顺序重要吗? –

+0

为什么你喜欢这种方法嵌套循环? –

+0

遍历顺序无关 – TheJackal

回答

0

这是我想出了2D:(它的Java,但转换为C#,你应该只用C#等价物来替换System.out.printMath.ceil

int n = 5, m = 3; 
for (int i = 0; i < 2*(m+n); i++) 
{ 
    int x1 = i/(m+2*n), 
     x2 = (i%(m+n))%n, 
     x3 = (int)Math.ceil(((m+i)%(m+n))/m/(1.0*n)); 

    System.out.print(x1*(n-1) + x2 * x3 + " "); 

    int y1 = i/(m+n) - i/(m+2*n), 
     y2 = x2, 
     y3 = (int)Math.ceil((i%(m+n))/n/(1.0*m)); 

    System.out.println(y1*(m-1) + y2 * y3); 
} 

当然上面可以如果你愿意,可以写成一个访问数组的单个语句。

请注意,由于(i%(m+n))%n,这只适用于如果n > m。最简单的解决方法可能是将其粘贴到一个函数中,该函数需要4个参数x,y,m,n,根据mn是否较大,这些参数可以轻松交换。

输出:

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

Live demo。如你所见,它可以重复4个角落单元格,如果没关系的话。

让我们来看看每个xi样子(不Math.ceil/(1.0*m)/(1.0*n)):

i x1 x2 x3 y1 y2 y3 
0 0 0 1 0 0 0 
1 0 1 1 0 1 0 
2 0 2 1 0 2 0 
3 0 3 2 0 3 0 
4 0 4 2 0 4 0 
5 0 0 0 0 0 1 
6 0 1 0 0 1 1 
7 0 2 0 0 2 1 
8 0 0 1 1 0 0 
9 0 1 1 1 1 0 
10 0 2 1 1 2 0 
11 0 3 2 1 3 0 
12 0 4 2 1 4 0 
13 1 0 0 0 0 1 
14 1 1 0 0 1 1 
15 1 2 0 0 2 1 

Math.ceil/(1.0*m)/(1.0*n)只是有改变和y3 1,他们是> 1 (如果适用的限制(mn)大于其他限制(nm),将发生这种情况

然后可以使用上表获得期望的遍历,方法是将第一个与the limit-1相乘,并添加第二个和第三个的乘积,如代码中的print语句所示。

搞清楚上面的表格是否有用,如何生成以及如何使用它只是一个问题。

是的,我没有搞清楚3D。

正如你所看到的东西略长的方式更具可读性:

int n = 5, m = 3; 
int x = 0, y = 0; 
int xInc = 1, yInc = 0; 
while (true) 
{ 
    System.out.println(x + " " + y); 
    // got to right, go down 
    if (x == n-1 && xInc == 1) 
    { 
     xInc = 0; 
     yInc = 1; 
    } 
    // got to bottom, go left 
    else if (y == m-1 && yInc == 1) 
    { 
     xInc = -1; 
     yInc = 0; 
    } 
    // got to left, go up 
    else if (x == 0 && xInc == -1) 
    { 
     xInc = 0; 
     yInc = -1; 
    } 
    // got to top, stop 
    else if (y == 0 && yInc == -1) 
    { 
     break; 
    } 
    x += xInc; 
    y += yInc; 
} 

输出:

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

假设顺时针或逆时针遍历,也许是这样,对于第一个指数:

for n = 5, m = 3. 
0 1 2 3 4 
11  5 
10 9 8 7 6 

For i = 0 to 2m + 2n - 5 
[ max(i - max(i - (n-1), 0) - max(i - (m+n-2), 0), 0) ] 

column index first increase from 0 to n-1 
Then it stays constant at n-1 upto i = n+m-2 
Then it decreases along with i to 0 upto i = 2n + m - 3 
Then again it stays constant at 0 upto 2n + 2m - 5. 

图为:

n-1_________ 
    /  \ 
/   \ 
/   \__________ 
0 n-1 n+m-2 2n+m-3 2n+2m-5 

对于第二指数: 图为:

 _______ 
    /  \ 
    /  \ 
____/   \ 
0 n n+m 2n+m 2n+2m 

你可以形成simil使用i的ar表达式。

+0

请详细说明这一点。我不明白你用过的图表。此外,对于基于零的数组,这可能会超出索引 – TheJackal

+0

@TheJackal我已在我的答案中添加了说明。请检查。 –