首页 > 解决方案 > 检查与二维阵列中的中间位置相关的不同大小的正方形的位置?

问题描述

array[i-1][j-1]
array[i-1][j]
array[i-1][j+1]

array[i][j-1]
array[i][j+1]

array[i+1][j-1]
array[i+1][j]
array[i+1][j+1]

我已经找到了一种检查 8 个相邻元素(上图)的方法,但我正在寻找是否有一种方法可以使它成为非硬编码的,以便我可以扩展检查,比如 2-3 个或更多单元格离开?我有一种直觉,嵌套的 for 循环可能会做到这一点,但我似乎无法让它工作

标签: javafor-loopnestedneighbours

解决方案


这是 C++ 中的解决方案。^^

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{

    int m[5][5]={1, 2, 3, 4,5,
                 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15,
                16, 17, 18, 19, 20,
                21, 22, 23, 24, 25};

    int n = 2; //number of cells you want to "move" from the origin
    int k=2;//for a cell in m[k][k]
    for(int i=1;i<=n;i++) //this is for the size of the "square" you form around the initial cell
    {
        cout<<i<<endl;
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k-i][k-j]<<" ";//cell of the first line, on top of the new formed "square"
        } 
        cout<<endl;
        for(int j=-i+1;j<=i-1;j++)
        {

        cout<< m[k+j][k-i]<<" ";//on the left side of the "square"
        cout<< m[k+j][k+i]<<endl;//on the right side of the "square"
        }
        for(int j=i;j>=-i;j--)
        {
            cout<<m[k+i][k-j]<<" ";//cell of the first line, on the bottom of the new formed "square"
        }
        cout<<endl;
    }
}

/**Result:
1
7 8 9 
12 14
17 18 19 
2
1 2 3 4 5 
6 10
11 15
16 20
21 22 23 24 25 */

推荐阅读