c语言魔方数组,二维数组魔方解决方案
C/C++ code// 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;
}
------解决方案--------------------
杨辉法(奇阶)
本法是由宋朝的杨辉在“续古摘奇算经” ( 西元 1275 ) 中给出的奇阶魔方阵造法。
针对三阶魔方阵的填制,杨辉用以下的歌谣来描述:
九子斜排,上下对易,
左右相更,四维挺进,
戴九履一,左三右七,
二四为肩,六八为足。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
