螺旋矩阵

暴力模拟填数字

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>

using namespace std;

int main()
{
    int n;
    int map[30][30];
    int num[30][30];
    while(cin>>n)
    {
        memset(map,0,sizeof(map));
        memset(num,0,sizeof(num));
        int d=0;
        int x=0;
        int y=0;
        int ans=1;
        int end=n*n+1;
        while(1)
        {
            if(d==0)
            {
                if(map[x][y]==0&&y<n)
                {
                    num[x][y]=ans;
                    map[x][y]=1;
                    ans++;
                    if(ans==end)
                    {
                        break;
                    }
                    y++;
                }
                else
                {
                    d=1;
                    x++;
                    y--;
                    continue;
                }
            }
            else if(d==1)
            {
                if(map[x][y]==0&&x<n)
                {
                    num[x][y]=ans;
                    map[x][y]=1;
                    ans++;
                    if(ans==end)
                    {
                        break;
                    }
                    x++;
                }
                else
                {
                    x--;
                    y--;
                    d=2;
                    continue;
                }
            }
            else if(d==2)
            {
                if(map[x][y]==0&&y>=0)
                {
                    num[x][y]=ans;
                    map[x][y]=1;
                    ans++;
                    if(ans==end)
                        break;
                    y--;
                }
                else
                {
                    y++;
                    x--;
                    d=3;
                    continue;
                }
            }
            else if(d==3)
            {
                if(map[x][y]==0&&x>=0)
                {
                    num[x][y]=ans;
                    map[x][y]=1;
                    ans++;
                    if(ans==end)
                        break;
                    x--;
                }
                else
                {
                    x++;
                    y++;
                    d=0;
                    continue;
                }
            }
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                printf("%4d",num[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

/*6
   1   2   3   4   5   6
  20  21  22  23  24   7
  19  32  33  34  25   8
  18  31  36  35  26   9
  17  30  29  28  27  10
  16  15  14  13  12  11
  */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值