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
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&#61;&#61;1) cout<<1<
cout<<1<<" "<<2<
else if(n%2!&#61;0){
for(i&#61;4-n/2;i<&#61;4&#43;n/2;i&#43;&#43;){
for(j&#61;4-n/2;j<&#61;4&#43;n/2;j&#43;&#43;){
if(j&#61;&#61;4&#43;n/2) cout< else
cout< }
cout<
}else{
for(i&#61;4-(n/2-1);i<&#61;4&#43;n/2;i&#43;&#43;){
for(j&#61;4-(n/2-1);j<&#61;4&#43;n/2;j&#43;&#43;){
if(j&#61;&#61;4&#43;n/2) cout< else
cout< }
cout<
}
}
return 0;
}
以上代码有点蛮干&#xff0c;下面才是正确的代码思路&#xff1a;
#include
using namespace std;
int d,x,y,a[1000][1000];
void move(){
switch(d){
case 0:
y&#43;&#43;;return;
case 1:
x&#43;&#43;;return;
case 2:
y--;return;
case 3:
x--;return;
}
}
int main(){
int n,c&#61;1;
cin>>n;
y&#61;x&#61;(n-1)/2;
a[x][y]&#61;c;
c&#43;&#43;;
d&#61;0;
move();
a[x][y]&#61;c;
c&#43;&#43;;
d&#61;(d&#43;1)%4;
for(int i&#61;1;i
a[x][y]&#61;c;
c&#43;&#43;;
}
d&#61;(d&#43;1)%4;
for(int j&#61;0;j move(); //再向左走i步
a[x][y]&#61;c;
c&#43;&#43;;
}
move(); //再向左走一步&#xff0c;此时d这个方向值不变
a[x][y]&#61;c;
c&#43;&#43;;
d&#61;(d&#43;1)%4;//走完之后方向发生改变
}
for(int i&#61;0;i
cout<
}