1044: 数圈
1044: 数圈
时间限制: 1 Sec 内存限制: 128 MB提交: 231 解决: 97
[提交][状态][讨论版]
题目描述
以1为中心,用2,3,4, ..., n, ..., n*n的数字围绕着中心输出数圈, 如若n=4,则
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
输入
输出
数圈矩阵
样例输入
5
样例输出
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
提示
来源
#include <iostream>
using namespace std;
int main(){
int i,j,n;
int a[10][10]={{73,74,75,76,77,78,79,80,81,82},
{72,43,44,45,46,47,48,49,50,83},
{71,42,21,22,23,24,25,26,51,84},
{70,41,20,7,8,9,10,27,52,85},
{69,40,19,6,1,2,11,28,53,86},
{68,39,18,5,4,3,12,29,54,87},
{67,38,17,16,15,14,13,30,55,88},
{66,37,36,35,34,33,32,31,56,89},
{65,64,63,62,61,60,59,58,57,90},
{100,99,98,97,96,95,94,93,92,91}};
while(cin>>n){
if(n==1) cout<<1<<endl;
else if(n==2){
cout<<1<<" "<<2<<endl;
cout<<4<<" "<<3<<endl;
}
else if(n%2!=0){
for(i=4-n/2;i<=4+n/2;i++){
for(j=4-n/2;j<=4+n/2;j++){
if(j==4+n/2) cout<<a[i][j];
else
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}else{
for(i=4-(n/2-1);i<=4+n/2;i++){
for(j=4-(n/2-1);j<=4+n/2;j++){
if(j==4+n/2) cout<<a[i][j];
else
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
}
return 0;
}
以上代码有点蛮干,下面才是正确的代码思路:
#include<iostream>
using namespace std;
int d,x,y,a[1000][1000];
void move(){
switch(d){
case 0:
y++;return;
case 1:
x++;return;
case 2:
y--;return;
case 3:
x--;return;
}
}
int main(){
int n,c=1;
cin>>n;
y=x=(n-1)/2;
a[x][y]=c;
c++;
d=0;
move();
a[x][y]=c;
c++;
d=(d+1)%4;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
move(); //某个方向走i步,如向下
a[x][y]=c;
c++;
}
d=(d+1)%4;
for(int j=0;j<i;j++){
move(); //再向左走i步
a[x][y]=c;
c++;
}
move(); //再向左走一步,此时d这个方向值不变
a[x][y]=c;
c++;
d=(d+1)%4;//走完之后方向发生改变
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(j==0)cout<<a[i][j];
else cout<<" "<<a[i][j];
}
cout<<endl;
}
}