SDUT 2254 字母螺旋方阵(递归)

来源:互联网 发布:c语言中static的用法 编辑:程序博客网 时间:2024/05/29 19:28

与之前做过的螺旋矩阵不同之处在于,n*m的矩阵,并且是在A-Z之间不停循环的问题。注意控制好边界如递归条件一直在l<=r&&up<=down 和tmp==cnt

#include <iostream>#include <cstring>#include<cmath>#include<cstdio>using namespace std;int cnt;int a[1100][1100];int n,m;void so(int up,int down,int l,int r,int s,int tmp){    int i;    if(l<=r&&up<=down)    {        for(i=l; i<=r; i++)        {            tmp++;            ++s;            if(s==27)                s=1;            a[up][i]=s;            if(tmp==cnt)            {                for(int x=1; x<=n; x++)                {                    for(int y=1; y<=m; y++)                    {                        int k=a[x][y];                        printf(" %c",64+k);                    }                    cout<<endl;                }                return ;            }        }        for(i=up+1; i<down; i++)        {            tmp++;            ++s;            if(s==27)            s=1;            a[i][r]=s;            if(tmp==cnt)            {              //  s=0;                for(int x=1; x<=n; x++)                {                    for(int y=1; y<=m; y++)                    {                        int k=a[x][y];                        printf(" %c",64+k);                    }                    cout<<endl;                }                return ;            }        }        for(i=r; i>=l; --i)        {            tmp++;            ++s;            if(s==27)                s=1;            a[down][i]=s;            if(tmp==cnt)            {                for(int x=1; x<=n; x++)                {                    for(int y=1; y<=m; y++)                    {                        int k=a[x][y];                        printf(" %c",64+k);                    }                    cout<<endl;                }                return ;            }        }        for(i=down-1; i>up; --i)        {            tmp++;            ++s;            if(s==27)                s=1;            a[i][l]=s;            if(tmp==cnt)            {                s=0;                for(int x=1; x<=n; x++)                {                    for(int y=1; y<=m; y++)                    {                        int k=a[x][y];                        printf(" %c",64+k);                    }                    cout<<endl;                }                return ;            }        }        so(up+1,down-1,l+1,r-1,s,tmp);    }    else    {        for(i=1; i<=n; i++)        {            for(int j=1; j<=m; j++)            {                int k=a[i][j];                printf(" %c",65+k);            }            cout<<endl;        }    }}int main(){    int i,j,k;    while(~scanf("%d%d",&n,&m))    {        cnt=n*m;        so(1,n,1,m,0,0);    }    return 0;}


0 0
原创粉丝点击