ICPC:螺旋方阵

题目描述

一个 n 行 n 列的螺旋方阵按如下方法生成:从方阵的左上角(第 1 行第 1 列)出发,初始时向右移动;如果前方是未曾经过的格子,则继续前进;否则,右转。重复上述操作直至经过方阵中所有格子。根据经过顺序,在格子中依次填入 1,2,3,…,n,便构成了一个螺旋方阵。下面是一个 n=4 的螺旋方阵。

 


编程输入一个正整数 n,生成一个 n×n 的螺旋方阵。

样例输入

5

样例输出

    1    2    3    4    5
   16   17   18   19    6
   15   24   25   20    7
   14   23   22   21    8
   13   12   11   10    9

代码

#include <bits/stdc++.h>

using namespace std;

int n;
int direction = 1;

void go(int &y, int &x, bool haha[][1000])
{

    bool flag = false;
    for(int time = 1; flag != true && time<=2;time++)
    {
        if (direction == 0)
        {
            if(y-1<1 || haha[y-1][x] == true)
            {
                direction = (direction+1)%4;
                continue;
            }
            y--;
            flag = true;
        }
        if (direction == 1)
        {
            if(x+1>n || haha[y][x+1] == true)
            {
                direction = (direction+1)%4;
                continue;
            }
            x++;
            flag = true;
        }
        if (direction == 2)
        {
            if(y+1>n || haha[y+1][x] == true)
            {
                direction = (direction+1)%4;
                continue;
            }
            y++;
            flag = true;
        }
        if (direction == 3)
        {
            if(x-1<1 || haha[y][x-1] == true)
            {
                direction = (direction+1)%4;
                continue;
            }
            x--;
            flag = true;
        }

    }
}

int main()
{

    cin>>n;
    int a[n+10][n+10];
    bool vis[n+10][1000] = {false};

    pair<int,int>position = {1,1};

    for(int i=1; i<=n*n; i++)
    {
        a[position.first][position.second] = i;
        vis[position.first][position.second] = true;
        go(position.first,position.second,vis);
    }

    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cout<<setw(5)<<a[i][j];
        }
        cout<<endl;
    }


    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值