现在的位置: 首页 > 综合 > 正文

逆时针顺序的螺旋矩阵打印

2013年08月21日 ⁄ 综合 ⁄ 共 1486字 ⁄ 字号 评论关闭

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/*
1   8    7
2   9    6
3   4    5
输出如图所示的矩正,第一个是3*3的,后面的4*4的,
算法就是随便输入一个N,就可以输出一个N*N的矩正???
1 12 11 10
2 13 16  9
3 14 15  8
4  5  6  7                                 */
void  MatrixProcess( int ** Matrix,int N )
{
    int number=1;
    int start=0,end=N,i; 
    assert( N > 1 );
    assert( Matrix != NULL ); 
 for(i=0; i < N/2+1; ++i)
 {
  int iter=0;  
  for( iter=start; iter<end; ++iter )
   if( Matrix[iter][start] == 0 )
    Matrix[iter][start]  = number++;
     for( iter= ++start; iter<end; ++iter )
       if( Matrix[end-1][iter] == 0 )
          Matrix[end-1][iter]  = number++;
        for( iter= --end;   iter>=start-1; --iter )
         if( Matrix[iter][end] == 0 )
           Matrix[iter][end]  = number++;
        for( iter= end; iter>=start; --iter )
         if( Matrix[start-1][iter] == 0 )
           Matrix[start-1][iter]  = number++;  
 }
}
int **  MatrixMemAlloc( int N )
{
 /* N为阶数,分配N*N的二维空间,清零 */
 int ** mem;
 int i,j;
 
 assert( N > 1 );
 mem =  (int **) malloc ( (sizeof(int *)) * N );
 assert(mem != NULL);
 
 for(i=0; i<N; ++i)
 {
  mem[i] = (int *) malloc ( (sizeof(int)) * N );
  assert( mem[i] != NULL );       
 }   
 for(i=0; i< N; ++i)
  for(j=0; j<N; ++j)
   mem[i][j]=0;  /*  清零 */
  
 return mem;  
}

/**/
void MatrixPrint(int ** Matrix,int N)
{
 /**/
 int i,j;
 
 assert( N>1 );
 assert( Matrix != NULL );
 
 for(i=0;i<N;++i)
  assert( Matrix[i] != NULL );
 
 for(i=0;i<N;++i)
 {
  for(j=0;j<N;++j)
   printf("%3d",Matrix[i][j]);
  printf("/n");
 }
 return;
}
/**/

int main()
{
 int N,** point;
 printf("input N:");
 scanf("%d",&N);
 
 point =  MatrixMemAlloc( N );
 MatrixProcess( point,N );
 MatrixPrint( point, N );
 
 system("PAUSE"); 
 return 0;
}

抱歉!评论已关闭.