c語言實現奇數魔方陣

魔方陣定義:魔方陣是一個方陣,它的每一行、每一列和對角線之和均相等。

例如存在三階魔方陣:

8   1   6

3   5   7

4   9   2

魔方陣中各數的排列規則:

(1)將1放在第一行中間一列。

(2)從2開始直到n*n止各數依次按照下列規則存放:每一個數存放的行比前一個數的行數減1,列數加1(例如上述的魔方陣中,6在5的上一行下一列)

(3)當上一個數的行數爲1時,下一個數的行數爲n,列數加1。(例如上述的魔方陣中,1在第一行,則2應該放在最後一行,列數同樣加1)

(4)當上一個數的列數爲n時,下一個數的行數減1,列數應該爲1。(例如在上述的魔方陣中,2在第三行最後一列,則3應該放在第二行第一列)

(5)如果按照上面規則確定的位置上已經有數,或者上一個數是第一行第n列的時候,則應該把下一個數放在上一個數的下面。(例如在上述的魔方陣中,按照規定,4應該放在第1行第2列,但該位置已被1佔據,所以4就放在3的下面。由於6是第1行第3列(即最後一列),故7放在6的下面)

詳細代碼如下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[16][16],i,j,k,p,n;
    p=1;

    //Input a odd number that between 1 and 15.
    while(p==1){
        printf("Please input a odd number that between 1 and 15.");
        scanf("%d",&n);
        if((n!=0)&&(n<=15)&&(n%2!=0))
            p=0;
    }
    //Initialization the matrix
    for(int i=1;i<=n;i++){
        for(j=1;j<=n;j++){
            a[i][j]=0;
        }
    }
    //Create the magic square
    i=1;
    j=n/2+1;
    a[1][j]=1;
    for(k=2;k<=n*n;k++){
        i=i-1;
        j=j+1;

        if((i<1)&&(j>n)){//If the position previous number is (1,n)
            i=i+2;
            j=j-1;
        }else{
            if(i<1) //If the rows of the previous number is 1.
                i=n;
            if(j>n) //If the cols of the previous number is n.
                j=1;
        }


        if(a[i][j]==0){ //If the position that we have select have no number.
            a[i][j]=k;
        }else{ //If the position that we have select have number.
            i=i+2;
            j=j-1;
            a[i][j]=k;
        }
    }
    //Print the number of the devil matrix.
    for(i=1;i<=n;i++){
        for(j=1;j<=n;j++){
            printf("%5d",a[i][j]);
        }
        printf("\n");
    }

    return 0;
}

以上是對奇數階的魔鬼方陣的總結,如果有不明白的地方,可以發送郵箱至[email protected]進行學習交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章