回形要求,中间空格,每一行后不得有空格,要求大小自己定义。
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,a[101][101];
cin>>n;
int count=0,i=1,j=1,x=1;//i,j记录数组的变量,x是圈数记录
int n1=n,i2=i,j2=j;//n1是圈范围变量,i2,j2是变圈后的循环变量,其不能与i,j搞混。
while(count<n*n){
if(i2!=n1&&j2!=n1){//该判断是入圈时机,不能用i,j代替,当且紧当i2,j2在最外圈(即x==1)才可代替。
for(int i1=1;i1<=n1-1;i1++){
a[i][j]=++count;
j++;
j2++;
}
}
else if(i2!=n1&&j2==n1){
for(int i1=1;i1<=n1-1;i1++){
a[i][j]=++count;
i++;
i2++;
}
//i++;
}
else if(i2==n1&&j2==n1){
for(int i1=1;i1<=n1-1;i1++){
a[i][j]=++count;
j--;
j2--;
}
//j--;
}
else if(i2==n1&&j2!=n1){
for(int i1=1;i1<=n1-1;i1++){
a[i][j]=++count;
i--;
i2--;
}
if(i==j){
i++;
j++;
x++;
n1-=2;
i2=1;
j2=1;
if(n1==1){
a[i][j]=++count;
break;
}
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j];
if(j==n){
cout<<endl;
}
else{
cout<<" ";
}
}
}
return 0;
}
写这段代码的时候老毛病又犯了,就是没有想清楚最佳的方法去写,总是想着矩阵拐角转弯时要加入if语句,行是行,可是有点傻啊。最后想到,反正是回形,每一次都有循环,何不直接四个循环就好了吗?当收缩一圈时,循环范围变小便可以了,下面是改进后的代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[100][100];
int count=0,first=0,_end=n-1;
while(count<n*n){
for(int i=first;i<_end;i++){
a[first][i]=++count;
}
for(int i=first;i<_end;i++){
a[i][_end]=++count;
}
for(int i=_end;i>first;i--){
a[_end][i]=++count;
}
for(int i=_end;i>first;i--){
a[i][first]=++count;
}
first++;_end--;
if(first==_end){
a[first][_end]=++count;
break;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<a[i][j];
if(j==n-1){
cout<<endl;
}
else{
cout<<" ";
}
}
}
return 0;
}
所以,在编写每一个问题的时候,一定要想要方法,可以在脑海里演算一遍,最后想出合适的算法再写,不然想我一样想到什么写什么很吃亏。