Java 检查与2D阵列中的中间位置相关的各种大小的方形中的位置?

Java 检查与2D阵列中的中间位置相关的各种大小的方形中的位置?,java,for-loop,nested,neighbours,Java,For Loop,Nested,Neighbours,我已经找到了一种方法来检查8个相邻的元素(如上),但我正在寻找是否有一种方法使其非硬编码,以便我可以扩展检查,比如说2-3个或更多的单元格?我有一个直觉,嵌套for循环可能会这样做,但是我不能让它工作。 < p>这是C++中的解决方案。^ ^ 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循环可能会这样做,但是我不能让它工作。

< p>这是C++中的解决方案。^ ^
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]
//示例程序
#包括
#包括
使用名称空间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;//要从原点“移动”的单元格数
int k=2;//对于m[k][k]中的单元格
对于(int i=1;i
// 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 */