输出螺旋矩阵

 1 #include <iostream>
 2 #include <iomanip>
 3 using namespace std;
 4 void main()
 5 {
 6 void f(int i,int j,int n,int value,int **a);
 7 int n,p,q;
 8 cout<<"Please input the value of n:"<<endl;
 9 int **a;
10     cin>>n;
11     a=new int*[n];
12     for(int i=0;i<n;i++)
13    a[i]=new int[n];
14 f(0,0,n,1,a);
15 for(p=0;p<n;p++)
16 {
17    for(q=0;q<n;q++)
18     cout<<setw(4)<<a[p][q];
19    cout<<endl;
20 }
21 }
22 void f(int i,int j,int n,int value,int **a)    //递归函数,观察得在外层a[i][j]+a[j][i]是一恒值
23 {
24 int v=value,i1=i,j1=j,sum,m=n;
25 a[i][j]=v;
26 a[i+1][j]=a[i1][j1]+4*n-5;
27 sum=a[i1+1][j1]+a[i1][j1]+1;
28 for(j1=j+1;j1<j+n;j1++)
29 {
30    a[i][j1]=++v;
31    a[j1][i]=sum-v;
32 }
33 for(i1=i+1;i1<i+n;i1++)
34 {
35    a[i1][j1-1]=++v;
36    a[j1-1][i1]=sum-v;
37 }
38 n=n-2;
39 value=a[i+1][j]+1;
40 i++;
41 j++;
42 if(n!=0&&n!=1)
43    f(i,j,n,value,a);
44 else
45    if(n==1)
46     a[i][j]=value;
47 }

 

posted @ 2009-12-01 20:16  mellowsmile  阅读(244)  评论(0编辑  收藏  举报