螺旋方阵
下面是一个5阶的螺旋方阵。编写程序打印此形式的n(n<10)阶的方阵。(顺时针方向旋进)
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
求大神分析给思路
#include <stdio.h> #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif unsigned foo( unsigned n, unsigned i, unsigned j ) { unsigned a = min( min(i,n-i-1), min(j,n-j-1) ); return (4*a*(n-a-1)+2*n-1) + (1-(i<=j)*2)*(2*n-2*a-i-j-2); } int main( void ) { const unsigned n = 5; for( size_t i=0; i!=n*n; ++i ) printf( "%4u%c", foo(n,i/n,i%n), " \n"[(i+1)%n==0] ); return 0; }
#include<stdio.h> #define N 5 int fun(int i,int j); int min(int a,int b); int main() { int i=0; int j=0; for (i=1;i<=N;++i,printf("\n")) for (j=1;j<=N;++j) printf("%4d%c",fun(i,j),"\n "[j!=N+1]); return 0; } int fun(int i,int j) { int a=min(min(i,N-i+1),min(j,N-j+1));//获取层数 //int sum=4*(a-1)*(N-a+1);//求层数里面所有数值相加的数值和 return i+j-2*(a-1)-1+4*(a-1)*(N-a+1)+2*(i>j)*((2*N-i-j)-2*(a-1)); } int min(int a,int b) { return (a<b?a:b); }
[此贴子已经被作者于2017-2-28 18:18编辑过]