簡體   English   中英

確定二維整數數組中的連續數字

[英]Determining Consecutive Numbers in a 2D Integer array

我有一個不同大小的二維數組,其中高度可以取任何值。

int array[][] = new int[height][height]

假設我有一個 3 x 3 數組,其值為:

7 8 9

6 5 4

1 2 3

是否可以檢查 1 是否與 2 相鄰、2 是否與 3 相鄰、3 是否與 4 相鄰、4 是否與 5 相鄰等等? 如果它們在垂直、水平和對角線上彼此相鄰,則此處相鄰。

所以基本上,有一個從 1 到 9(或最大數量 - 例如,如果板是 4x4,則從 1 到 16)的鏈接。

這是我能夠做到的。 這是一個很好的解決方案,雖然需要更多空間。 不過,這絕對不是最好的解決方案。 可能需要使用數學來獲得更優化的解決方案。 我數學不是很好。

//assuming the height as variable - 'r'
//take an input of some element, let's assume a[0][0], taken inside a[e][e]

int f, f1, f2, arflg=0;
int arr = new int[r*r];
for(int i=0;i<r;i++){
    for(int j=0;j<r;j++){
        arr[arflg]=a[i][j];
        arflg++;
        if(a[i][j]==a[e][e]) f1 = arflg; //location of element entered on the array
        if(a[i][j]==a[e][e]-1) f2 = arflg; //location of element's predecessor on the array
    }
}
f = f2 - f1;
if(f==1){
//forward hortizontal
}elseif(f==-1){
//backward horizontal
}elseif(f==r){
//below
}elseif(f==r-1){
//below left
}elseif(f==r+1){
//below right
}elseif(f==-r){
//above
}elseif(f==(-r-1)){
//above left
}elseif(f==(-r+1){
//above right
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM