螺旋矩阵

来源:互联网 发布:php上传文件error 0 编辑:程序博客网 时间:2024/04/29 22:47

//采用递归算法

 #include<iostream.h>
void luoxuan(int **pt,int n,int left,int right,int top,int bottom,int m);
int main()
{
    int n=5,i,j;
    //分配空间
    int **p=new int*[n];
    for(i=0;i<n;i++)
    {
        p[i]=new int[n];
    }
    luoxuan(p,n,0,n-1,0,n-1,1);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            cout<<p[i][j];
            cout<<"/t";
        }
        cout<<endl<<endl;
    }
    //释放空间
    for(i = 0; i < n; i++)
        delete []p[i];
    delete []p;

    return 0;
}
void luoxuan(int **pt,int n,int left,int right,int top,int bottom,int m)
{
    int i;
    if(left<right)
    {
         for(i=left;i<right;i++)
         {
             pt[top][i]=m++;
         }
         for(i=top;i<bottom;i++)
         {
             pt[i][right]=m++;
         }
         for(i=right;i>left;i--)
         {
             pt[bottom][i]=m++;
         }
         for(i=bottom;i>top;i--)
         {
             pt[i][left]=m++;
         }
         luoxuan(pt,n,left+1,right-1,top+1,bottom-1,m);
    }
    if(left==right)
          pt[top][left]=m++;
}

原创粉丝点击