- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #define GET_XY(x,y,n) ((y)*(n)+(x))
- char *Cmd;
- struct mm
- {
- int x;
- int y;
- } Mm[4] = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };
- void
- rotate_mm( int r )
- {
- struct mm m;
- r %= 4;
- if( r == 1 )
- {
- m = Mm[0];
- Mm[0] = Mm[1];
- Mm[1] = Mm[2];
- Mm[2] = Mm[3];
- Mm[3] = m;
- }
- else if( r == 2 )
- {
- m = Mm[0];
- Mm[0] = Mm[2];
- Mm[2] = m;
- m = Mm[1];
- Mm[1] = Mm[3];
- Mm[3] = m;
- }
- else if( r == 3 )
- {
- m = Mm[0];
- Mm[0] = Mm[3];
- Mm[3] = Mm[2];
- Mm[2] = Mm[1];
- Mm[1] = m;
- }
- return;
- }
- int *
- make_matrix( int n )
- {
- int *im;
- int i;
- int x, y;
- int m;
- int d, l;
- if( ( n - 1 ) % 2 )
- {
- fprintf( stderr, "[%d] is not odd!\n", n );
- return( (int *) NULL );
- }
- if( ( im = (int *) malloc( n*n*sizeof(int) ) ) == (int *) NULL )
- {
- fprintf( stderr, "malloc error: %s\n", strerror(errno) );
- return( (int *) NULL );
- }
- x = y = n / 2;
- m = 0;
- d = 0;
- l = 1;
- for( i = 1; i <= n*n; i++ )
- {
- im[GET_XY(x,y,n)] = i;
- x += Mm[m].x;
- y += Mm[m].y;
- if( ++d == l )
- {
- if( m % 2 )
- l++;
- m = ( m + 1 ) % 4;
- d = 0;
- }
- }
- return( im );
- }
- int
- get_digits( int n )
- {
- if( n / 10 )
- return( get_digits( n / 10 ) + 1 );
- else
- return( 1 );
- }
- static void
- prt_help()
- {
- fprintf( stderr, "Usage:%s [-r type] [-h] num\n", Cmd );
- return;
- }
- int
- main( int ac, char **av )
- {
- int c;
- int errflag = 0;
- int r = 0;
- int *im;
- int n;
- int d;
- int i;
- if( ( Cmd = strrchr( av[0], '/' ) ) == NULL )
- Cmd = av[0];
- else
- Cmd++;
- while( ( c = getopt( ac, av, ":hr:" ) ) != -1 )
- {
- switch( c )
- {
- case 'r':
- r = atoi(optarg);
- if( r < 1 || r > 3 )
- {
- fprintf( stderr, "%s: type in 1,3\n", Cmd );
- errflag++;
- }
- break;
- case 'h':
- errflag++;
- break;
- case ':': /* argument for option is missing */
- errflag++;
- fprintf( stderr, "%s: option -%c need argument\n",
- Cmd, optopt );
- break;
- case '?': /* option is not in option set */
- errflag++;
- fprintf( stderr, "%s: option -%c is unknown \n",
- Cmd, optopt);
- }
- }
- if( errflag )
- {
- prt_help( );
- exit( 1 );
- }
- if( optind != ac - 1 )
- {
- prt_help( );
- exit( 1 );
- }
- n = atoi(av[optind]);
- if( r )
- rotate_mm( r );
- if( ( im = make_matrix( n ) ) == (int *) NULL )
- {
- fprintf( stderr, "%s: make_matrix error!\n", Cmd );
- exit( 1 );
- }
- d = get_digits( n * n );
- printf( "%d\n", n );
- for( i = 0; i < n*n; i++ )
- {
- printf( "%-*d ", d, *im++ );
- if( i % n == n - 1 )
- printf( "\n" );
- }
- printf( "\nIt's OK\n" );
- free( im - n * n );
- return( 0 );
- }
复制代码 用以前的程序架构完成的,算法部分其实很简单,人是怎么想的,程序就怎么跑 |
|