写的有点乱了 #include <iostream>#include <assert.h>#include <iomanip>using namespace std;int main(){ //define the directions const int right=1; const int down=2; const int left=3; const int up=4; //current direction int direction; //size of the matrix int n; //input the size of the matrix cout<<"input size of the matrix:"<<endl; cin>>n; //dynamically create the 2D array int **p=new int*[n]; for(int i=0;i<n;i++) *(p+i)=new int[n]; for(int i=0;i<n;i++) for(int j=0;j<n;j++) p[i][j]=0; int value=1; direction=right; int row=0,col=0; while(true) { p[row][col]=value; switch(direction) { case right: ++col; if(col==n) { col--; direction++; break; } if(p[row][col]!=0) { col--; direction++; break; } value++; break; case down: ++row; if(row==n) { row--; direction++; break; } if(p[row][col]!=0) { row--; direction++; break; } value++; break; case left: --col; if(col==-1) { col++; direction++; break; } if(p[row][col]!=0) { col++; direction++; break; } value++; break; case up: --row; if(row==-1) { row++; direction++; break; } if(p[row][col]!=0) { row++; direction++; break; } value++; break; default: break; } if(value==n*n) { p[row][col]=value; break; } if(direction>4) direction%=4; } int output_width=n*n; int num_digits=1; //determine the width of the element while(true) { if(output_width==0) break; else { output_width/=10; num_digits++; } } //ouput matrix for(int i=0;i<n;i++) { for(int j=0;j<n;j++) cout<<setiosflags(ios::left)<<setw(num_digits)<<p[i][j]; cout<<endl; } //destroy 2D array for(int i=0;i<n;i++) delete []*(p+i); delete []p; return 0;} 输出: input size of the matrix:91 2 3 4 5 6 7 8 932 33 34 35 36 37 38 39 1031 56 57 58 59 60 61 40 1130 55 72 73 74 75 62 41 1229 54 71 80 81 76 63 42 1328 53 70 79 78 77 64 43 1427 52 69 68 67 66 65 44 1526 51 50 49 48 47 46 45 1625 24 23 22 21 20 19 18 17

评论