求螺旋矩阵

来源:互联网 发布:网络咨询护士工资多少 编辑:程序博客网 时间:2024/05/19 00:13

求螺旋矩阵

下图是一个n = 4 时的螺旋矩阵。 


#include <iostream>

#include <cstdio>

#include <string>

#include <cstring>

#include <set>

#include <cmath>

#include <algorithm>

using namespace std;

int a[10005],b[10005][105];

int main()

{

   int s,m,n,x,y;

   scanf("%d",&s);

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

       scanf("%d",&a[i]);

   x=s,y=1;

   memset(b,0,sizeof(b));

   for(int i=s; x>=y&&i>0 ; i--)

   {

       if(s%i==0)

       {

            if(i>=s/i)

            {

                m=i;

                n=s/i;

            }

            x=i;

            y=s/i;

       }

   }

   sort(a,a+s,greater<int>());

   int j=0;

   x=0,y=0;

   while(j<s)

    {

       while(y<n&&!b[x][y])

           b[x][y++]=a[j++];

       y--;

       x++;

       while(x<m&&!b[x][y])

           b[x++][y]=a[j++];

       x--;

       y--;

       while(y>=0&&!b[x][y])

           b[x][y--]=a[j++];

       y++;

       x--;

       while(x>=0&&!b[x][y])

           b[x--][y]=a[j++];

       x++;

       y++;

    }

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

   {

       for(j=0;j<n-1;j++)

            cout<<b[i][j]<<"";

       cout<<b[i][j]<<endl;

   }

   return 0;

}

0 0
原创粉丝点击