【C++_Practice】螺旋数字正方形

/*
 螺旋数字正方形
 
 题目描述
 打印螺旋数字正方形
 
 
 输入描述
 输入一个整数n,1<=n<=31
 
 
 输出描述
 输出数字正方形。
 
 注意,每个数字占4个字符,右对齐,不全则补足空格;
 */

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

void setMatrix(int **matrix, int x, int y, int start, int n)
{
    if(n <= 0)
        return;
    if(n == 1)
    {
        matrix[x][y] = start;
        return;
    }//上边
    for(int j = y; j< n + y - 1; ++j)
    {
        matrix[x][j] = start ++;
    }//右边
    for(int i = x; i < x + n - 1; ++ i)
    {
        matrix[i][n + x - 1] = start ++;
    }
    for(int j = n + y - 1; j > y; --j)
    {
        matrix[n + x - 1][j] = start ++;
    }
    for(int i = x + n - 1; i > x; -- i)
    {
        matrix[i][y] = start ++;
    }
    setMatrix(matrix, x + 1, y + 1, start, n - 2);
}

int main()
{
    int n;
    cin >> n;
    if(n >= 1 && n <= 31)
    {
        int **matrix = new int*[n];
        for(int i = 0; i < n; i ++)
        {
            matrix[i] = new int[n];
        }
        setMatrix(matrix, 0, 0,1, n);
        for(int i = 0; i < n; i ++)
        {
            for(int j = 0; j < n; j ++)
                cout << setw(4) << matrix[i][j];
            cout << endl;
        }
    }
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30638419/article/details/85405081