#include <iostream> #define max 10000 using namespace std; int G[max][max]; int main() { int n; cin>>n; int count; if(n%2==0)count=n/2; else count=n/2+1; int ans = 1; for(int t = 0;t < count;t++){ for(int i = t;i < n-t;i++) G[t][i]=ans++; for(int j = t+1;j < n-t;j++) G[j][n-1-t]=ans++; for(int i = n-2-t;i>=t;i--) G[n-1-t][i]=ans++; for(int j = n-2-t;j>t&&ans<n*n;j--) G[j][t]=ans++; } for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ cout<<G[i][j]<<" "; } } return 0; }
效果图:
敲代码还是要戒骄戒躁,一着急就啥都不行了,唉
改进,输入的是长m和宽n,得到目的矩阵
同时实现的是字母的方式
1 #include <iostream> 2 #include <stdio.h> 3 #define max 1000 4 5 using namespace std; 6 7 int G[max][max]; 8 int main() 9 { 10 int m,n; 11 cin>>n>>m; 12 int tian = (m>n)?n:m; 13 if(tian%2==1)tian++; 14 int count = 0; 15 16 for(int i = 0;i < tian/2; i++){ 17 for(int x = i;x<=m-1-i;x++){ 18 G[i][x]=(++count); 19 } 20 for(int y = i+1;y<=n-1-i;y++){ 21 G[y][m-1-i]=(++count); 22 } 23 for(int x = m-2-i;x>=i&&n-1-i>i;x--){ 24 G[n-1-i][x]=(++count); 25 } 26 for(int y = n-2-i;y>=i+1&&i<m-1-i;y--){ 27 G[y][i]=(++count); 28 } 29 } 30 cout<<endl; 31 for(int i = 0;i < n;i++){ 32 for(int j = 0;j < m;j++){ 33 // printf("%.3d",G[i][j]); 34 cout<<G[i][j]<<" "; 35 } 36 cout<<endl; 37 } 38 39 for(int i = 0;i < n;i++){ 40 for(int j = 0;j < m;j++){ 41 cout<<char('A'+((G[i][j]-1)%26))<<" "; 42 } 43 cout<<endl; 44 } 45 return 0; 46 }
PAT中代码新解:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cmath> 5 #define MAXN 1000006 6 #define MINN 1003 7 using namespace std; 8 bool cmp(int a,int b){ 9 return a>b; 10 } 11 int input[MAXN],output[MINN][MINN]; 12 int main() 13 { 14 int n,i,a,b,c,index; 15 scanf("%d",&n); 16 17 if(!n){ 18 printf("\n"); 19 return 0; 20 } 21 for(int i=1;i<=n;i++) 22 scanf("%d",&input[i]); 23 sort(input+1,input+n+1,cmp); 24 for(i=(int)sqrt(n);n%i;i--); 25 a=i,b=n/i; 26 (a%2)?(c=(a/2+1)):(c=(a/2)); 27 index=0; 28 for(int i=1;i<=c&&index<n;i++){ 29 for(int k=1+i-1;k<=a+1-i&&index<n;k++){ 30 output[i][k]=input[++index]; 31 //output[i][k]=++index; 32 } 33 for(int k=1+i;k<=b-i+1&&index<n;k++){ 34 output[k][a-i+1]=input[++index]; 35 //output[k][a-i+1]=++index; 36 } 37 for(int k=a-i;k>=i&&index<n;k--){ 38 output[b-i+1][k]=input[++index]; 39 //output[b-i+1][k]=++index; 40 } 41 for(int k=b-i;k>i&&index<n;k--){ 42 output[k][i]=input[++index]; 43 //output[k][i]=++index; 44 } 45 } 46 for(int i=1;i<=b;i++) 47 for(int j=1;j<=a;j++) 48 if(j!=a)printf("%d ",output[i][j]); 49 else printf("%d\n",output[i][j]); 50 return 0; 51 }
pat题目: