革命尚未成功

————同志仍需努力————

shinnyblue

导航

P5731 蛇形方阵

P5731 【深基5.习6】蛇形方阵 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

//为什么用动态二维数组   --->To play to user's input, but it's alright without using dynamical array as long as you don't initiate all of them as zero.
//动态二维数组怎么用(申明、删除)    ---> To be formulated in a new essay, sooner or later.
#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
int n,x,y,value;//y横向,x纵向
int main()
{
    cin>>n;
    int **a=new int*[n];
    for (size_t i = 0; i < n; i++)
    {
        a[i]=new int[n];
        memset(a[i],0,n*sizeof(int));
    }
    x=y=0;
    value=a[0][0]=1;
    while (value<n*n)
    {
        while (y+1<n&&!a[x][y+1])//向右
        {                           //y+1<n是为了不超过边界,a[x][y+1]==0是控制及时拐弯
            a[x][++y]=++value;
        }
        while (x+1<n&&!a[x+1][y])//向下
        {
            a[++x][y]=++value;
        }
        while (y-1>=0&&!a[x][y-1])//向左
        {
            a[x][--y]=++value;
        }
        while (x-1>=0&&!a[x-1][y])//向上
        {
            a[--x][y]=++value;
        }
    }
    for (size_t i = 0; i < n; i++)
    {
        for (size_t j = 0; j < n; j++)
        {
            cout<<setw(3)<<a[i][j];
        }
        cout<<endl;
    }
    for (size_t i = 0; i < n; i++)
    {
        delete[] a[i];
    }
    delete[] a;
    
    return 0;
}

 

posted on 2023-02-18 13:08  ShinnyBlue  阅读(47)  评论(0)    收藏  举报

Live2D