serpentine fill

Description Fill in 1,2,...,n*n in the n*n square Chen, and it is required to fill in the shape of a snake. For example, when n=4, the formula is:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
enter
Directly enter the dimension of Fang Chen, that is, the value of n. (n<=100)
output
The output is a snake-shaped square Chen.
sample input
3
Sample output
7 8 1
6 9 2
5 4 3
source
Algorithm Classic
Uploaded by
CEO
code show as below:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=101;
int a[maxn][maxn]={0};
int main()
{
    int m, i, x , y ;
    while(scanf("%d",&m)!=EOF){
        memset(a,0,sizeof(a));
        i=a[0][m-1]=1;
        x=0;y=m-1;
        while(i<m*m){
            while(x+1<m && !a[x+1][y]){       //右
                a[++x][y]=++i;
                //printf("%d %d %d\n",x,y,a[x][y]);
            }
            while(y-1>=0 && !a[x][y-1]){       //下
                a[x][--y]=++i;
                //printf("%d %d %d\n",x,y,a[x][y]);
            }
            while(x-1>=0 && !a[x-1][y]){       //左
                a[--x][y]=++i;
                //printf("%d %d %d\n",x,y,a[x][y]);
            }
            while(y+1<m && !a[x][y+1]){       //上
                a[x][++y]=++i;
                //printf("%d %d %d\n",x,y,a[x][y]);
            }
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<m;j++)
            {
                printf("%2d ",a[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324643767&siteId=291194637