题目描述
在n×n的方阵中填入1、2、3、……、n×n(n<50),形成如下的蛇形方阵。例如:n=5的蛇形方阵为:
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5
输入
一个整数n
输出
n×n的蛇形方阵。(每一行数字之间一个空格隔开)
我编出来的代码如下:
#include<bits/stdc++.h>
using namespace std;
const int mxn = 105;
int a[mxn][mxn];
int main()
{
int n, s = 1;
cin >> n;
int x = 1, y = 1;
memset(a, 0, sizeof(a));
a[x][y] = s;
while(s < n * n)
{
while(((y + 1) <= n) && (a[x][y + 1] == 0))
{
y++;
s++;
a[x][y] = s;
}
while(((x + 1) <= n) && (a[x + 1][y] == 0))
{
x++;
s++;
a[x][y] = s;
}
while(((y - 1) >= 1) && (a[x][y - 1] == 0))
{
y--;
s++;
a[x][y] = s;
}
while(((x - 1) >= 1) && (a[x - 1][y] == 0))
{
x--;
s++;
a[x][y] = s;
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
代码输出如下:
5
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
请问各位朋友谁可以帮我找出我代码中哪里错了?
感谢!