2 visual studio1 VISUAL_STUDIO1 于 2016.01.30 22:03 提问

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

以下是代码,麻烦大神看一下有没有错
输入:n = 4;
结果:14 15 16 1
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
caozhy   Ds   Rxr 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;
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!