VISUAL_STUDIO1 于 2016.01.30 22:03 提问

C++蛇形填数问题， 输出有问题

0 0 0 2
0 0 0 3
7 6 5 4

`````` #include <iostream>
#include <iomanip>
#define maxn 20
using namespace std;
int str[maxn][maxn];
int main()
{
cout << "输入方阵：";
int n;
cin >> n;
int x = 0, y = n - 1, tot = 1;
memset(str,  0,  sizeof(str));
str[0][n - 1] = 1;
while (tot < n * n)
{
while (x+1< n  && str[x+1][y] == 0)
str[++x][y] = ++tot;//down move
while (y+1>= 0 && str[x][y-1] == 0)
str[x][--y] = ++tot;//left move
while (x - 1 >= 0 && str[x - 1][y] == 0)
str[--x][y] = ++tot;//up move
while (y + 1 < n  && str[x][y + 1] == 0)
str[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
cout << setw(5) << str[x][y];
cout << endl;
}
system("pause");
return 0;
}
``````

1个回答

caozhy      2016.01.30 23:26

`````` #include <iostream>
#include <iomanip>
#define maxn 20
using namespace std;
int str[maxn][maxn];
int main()
{
cout << "输入方阵：";
int n;
cin >> n;
int x = 0, y = n - 1, tot = 1;
memset(str,  0,  sizeof(str));
str[0][n - 1] = 1;
while (tot < n * n)
{
while (x+1< n  && str[x+1][y] == 0)
str[++x][y] = ++tot;//down move
while (y-1>= 0 && str[x][y-1] == 0) //修改
str[x][--y] = ++tot;//left move
while (x - 1 >= 0 && str[x - 1][y] == 0)
str[--x][y] = ++tot;//up move
while (y + 1 < n  && str[x][y + 1] == 0)
str[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
cout << setw(5) << str[x][y];
cout << endl;
}
system("pause");
return 0;
}
``````