螺旋输出N*N矩阵

#include <iostream>

#include <iomanip>

using namespace std;

void func(int n){

    static const int dir[][2]={{0,1},{1,0},{0,-1},{-1,0}};

    const int size=n+2;

    int **ver=new int *[size];

    for (int i=0;i<size;++i)

    {

       ver[i]=new int[size];

       if (i==0||i==size-1)

       {

           memset(ver[i],-1,size*sizeof(int));

       }

       else{

           memset(ver[i],0,size*sizeof(int));

           ver[i][0]=-1;

           ver[i][size-1]=-1;

       }     

    }

    int iIndex=0;

    int max=n*n;

    int cnt=1;

    int i=1,j=1;

    while (cnt<=max)

    {

       while (ver[i][j]==0)

       {

           ver[i][j]=cnt;

           i+=dir[iIndex][0];

           j+=dir[iIndex][1];

           ++cnt;

       }

       i-=dir[iIndex][0];

       j-=dir[iIndex][1];

       if (cnt>max)

       {

           break;

       }

       iIndex=(iIndex+1)%4;

       i+=dir[iIndex][0];

       j+=dir[iIndex][1];

       while (ver[i][j]!=0)

       {

           iIndex=(iIndex+1)%4;

           i+=dir[iIndex][0];

           j+=dir[iIndex][1];

       }

    }

 

 

    for (int i=1;i<size-1;++i)

    {

       for (int j=1;j<size-1;++j)

       {

           cout<<setw(6)<<ver[i][j];

       }

       cout<<endl;

    }

}

int main(){

    int n;

    cin>>n;

    func(n);  

}

10
     1     2     3     4     5     6     7     8     9    10
    36    37    38    39    40    41    42    43    44    11
    35    64    65    66    67    68    69    70    45    12
    34    63    84    85    86    87    88    71    46    13
    33    62    83    96    97    98    89    72    47    14
    32    61    82    95   100    99    90    73    48    15
    31    60    81    94    93    92    91    74    49    16
    30    59    80    79    78    77    76    75    50    17
    29    58    57    56    55    54    53    52    51    18
    28    27    26    25    24    23    22    21    20    19

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值