【急!!】关于#c++#的问题:打印如图的由内向外的螺旋方阵

求助急!!!

题目
 输入n,打印如图的由内向外的螺旋方阵

样例

输入
n=4


输出
| 16 | 15 | 14 | 13 |
| 5 | 4 | 3 | 12 |
| 6 | 1 | 2 | 11 |
| 7 | 8 | 9 | 10 |

你题目的解答代码如下:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int n,i,j,x=0,y=0,tx,ty,d=0;
    int ds[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
    cin >> n;
    int a[n][n];
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            a[i][j] = -1;
    for (i = n*n; i >= 1; i--)
    {
        a[y][x] = i;
        ty = y + ds[d][0];
        tx = x + ds[d][1];
        if (ty<0 || ty>=n || tx<0 || tx>=n || a[ty][tx]!=-1)
            d = (d+1)%4;
        y = y + ds[d][0];
        x = x + ds[d][1];
    }
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            cout << setw(5) << a[i][j];
        }
        cout << endl;
    }
    return 0;
}

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int n;
    cout << "Please input odd number" << endl;
    while (cin >> n && n % 2 == 0)
    {
        cout << "Please input odd number" << endl;
    }
    int** a = new int* [n];
    for (int i = 0; i < n; i++)
    {
        a[i] = new int[n];
    }
    int circle = 2, row = n / 2, col = n / 2, range = n / 2;
    a[row][col] = 1;
    int i = 1;


    while (range)
    {
        i = i + 1;
        col = col + 1;
        a[row][col] = i;


        for (int j = 0; j < circle - 1; j++)
        {
            i = i + 1;
            row = row + 1;
            a[row][col] = i;
        }


        for (int j = 0; j < circle; j++)
        {
            i = i + 1;
            col = col - 1;
            a[row][col] = i;
        }


        for (int j = 0; j < circle; j++)
        {
            i = i + 1;
            row = row - 1;
            a[row][col] = i;
        }


        for (int j = 0; j < circle; j++)
        {
            i = i + 1;
            col = col + 1;
            a[row][col] = i;
        }
        circle = circle + 2;
        range = range - 1;
    }
    for (int j = 0; j < n; j++)
    {
        for (int k = 0; k < n; k++)
        {
            cout << left << setw(5) << a[j][k];
        }
        cout << endl;
    }
    return 0;
}

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632