33,027
社区成员




// huangfang.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
void setvalue( unsigned char *hf, int howmuch, int x, int y, unsigned char value )
{
//填幻方矩阵
*( hf + ( y - 1 ) * howmuch + ( x - 1 ) ) = value;
}
unsigned char getvalue( unsigned char *hf, int howmuch, int x, int y )
{
//填幻方矩阵
return *( hf + ( y - 1 ) * howmuch + ( x - 1 ) );
}
int printhf( int howmuch )
{
if( howmuch > 9 ) //太多了不考虑
{
return 1;
}
if( !( howmuch % 2 ) ) //只考虑奇数的
{
return 1;
}
unsigned char buf[ 100 ] = ""; //100个足够了,相当于10 * 10了
int i, j;
int x, y;
for( i = 1; i <= howmuch * howmuch; i++ )
{
if( 1 == i )
{
//第一个,x当然中间的一个,Y就是第一行
x = ( howmuch / 2 ) + 1;
y = 1;
setvalue( buf, howmuch, x, y, i );
}
else
{
if( x == howmuch + 1 && 0 == y )
{
//右上角
x--;
y++;
y++;
}
if( y < 1 )
{
//向上出界了,应该转到最下面
y = howmuch;
}
if( x > howmuch )
{
//向右出界了,应该转到最左边
x = 1;
}
if( getvalue( buf, howmuch, x, y ) )
{
//如果这个位置已经添上了,使用正下一个
x--;
y++;
y++;
}
setvalue( buf, howmuch, x, y, i );
}
//填完之后,X++,Y--,向右上角上台阶嘛
x++;
y--;
}
for( i = 0; i < howmuch; i++ )
{
for( j = 0; j < howmuch; j++ )
{
printf( " %2d ", *( buf + i * howmuch + j ) );
}
printf( "\r\n" );
}
printf( "\r\n" );
printf( "\r\n" );
return 0;
}
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
for( int i = 3; i < 11; i += 2 )
{
printhf( i );
}
return 0;
}
8 1 6
3 5 7
4 9 2
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
47 58 69 80 1 12 23 34 45
57 68 79 9 11 22 33 44 46
67 78 8 10 21 32 43 54 56
77 7 18 20 31 42 53 55 66
6 17 19 30 41 52 63 65 76
16 27 29 40 51 62 64 75 5
26 28 39 50 61 72 74 4 15
36 38 49 60 71 73 3 14 25
37 48 59 70 81 2 13 24 35