魔方代码帮助,想知道它将数字向下移动的位置 C 语言编程


# include <stdio.h>
# include <stdlib.h>
int main(void)
{  
int s;
int row;
int column;
int k;
int array[99][99] ;
printf("Enter the dimension of the square : ") ;
scanf("%d", &s) ;
if (s % 2 == 0)
{
printf("Please enter an even number") ;
goto last;
}

column = (s + 1) / 2 ;
row = 1 ;
int sqr1 = s*s;
for(k = 1 ; k <= sqr1 ; k++)
{
array[row][column] = k ;
if(k % s == 0)
{
    row = (row + 1);
    goto loop ;
}
if(row == 1)
    row = s ;
else
         row = row - 1 ;
if(column == s)
    column = 1;
else
    column = column + 1 ;
    loop : ;
}
for (row = 1 ; row <= s ; row++)
{
for (column = 1 ; column <= s ; column++)
    {
    printf("%dt", array[row][column]) ;
}
printf("nn") ;
}
last : ;
return 0;
}

我想知道是否有人可以告诉我代码在哪里放下数字。假设我想要一个 3x3 魔方。输出将是:

https://i.stack.imgur.com/BYTSn.png

我想知道它会在代码中的哪个位置将 4 向下移动,因为 1 已经存在。7 向下移动也是如此。原则是你每次都向上走1,向右走1,如果那里有什么东西,你就向下移动并继续前进。

怎么样:

#include <stdio.h>
#include <string.h>
#define  N  (3)
int main( int argc, char * argv[] )
{
    int square[ N ][ N ];
    int i = N / 2;
    int j = N - 1;
    int num = 1;
    memset( square, 0, sizeof(square) );
    while( num <= N * N )
    {
        if( (i == -1) && (j == N) )
        {
            i = 0;
            j = N - 2;
        }
        else
        {
            if( i < 0 )
                i = N - 1;
            if( j == N )
                j = 0;
        }
        if( square[i][j] )
        {
            i++;
            j = j - 2;
            continue;
        }
        else
        {
            square[i][j] = num;
            num++;
        }
        j++;
        i--;
    }
    printf("N   = %dn", N );
    printf("Sum = %dnn", N * (N * N + 1) / 2 );
    for( i = 0; i < N; i++ )
    {
        for( j = 0; j < N; j++ )
            printf("%3d ", square[i][j]);
        printf("n");
    }
    return 0;
}

输出:

N   = 3
Sum = 15
  2   7   6 
  9   5   1 
  4   3   8 
N   = 5
Sum = 65
  9   3  22  16  15 
  2  21  20  14   8 
 25  19  13   7   1 
 18  12   6   5  24 
 11  10   4  23  17
N   = 7
Sum = 175
 20  12   4  45  37  29  28 
 11   3  44  36  35  27  19 
  2  43  42  34  26  18  10 
 49  41  33  25  17   9   1 
 40  32  24  16   8   7  48 
 31  23  15  14   6  47  39 
 22  21  13   5  46  38  30 
N   = 9
Sum = 369
 35  25  15   5  76  66  56  46  45 
 24  14   4  75  65  55  54  44  34 
 13   3  74  64  63  53  43  33  23 
  2  73  72  62  52  42  32  22  12 
 81  71  61  51  41  31  21  11   1 
 70  60  50  40  30  20  10   9  80 
 59  49  39  29  19  18   8  79  69 
 48  38  28  27  17   7  78  68  58 
 37  36  26  16   6  77  67  57  47 

引用:

  1. https://en.wikipedia.org/wiki/Siamese_method

  2. https://en.wikipedia.org/wiki/Magic_square

最新更新