3-3 Number of serpentine fill program

Serpentine number of fill. 1 in filled square in n * n, ..., n * n, serpentine fill requirements, the input is an integer n, the output is a square matrix. For example when n = 4 is square:


                                                   10 11 12   1 
                                                   9   16 13   2
                                                   8   15 14   3
                                                   7    6   5   4

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 8
int a[maxn][maxn];
int main()
{
    int n,x,y,sum=0;
    cin>>n;
    memset(a,0,sizeof(a));
    sum=a[x=0][y=n-1]=1;
    while(sum<n*n)
    {
        while(x+1<n&&!a[x+1][y])
        {
            a[++x][y]=++sum;
        }
        while(y-1>=0&&!a[x][y-1])
        {
            a[x][--y]=++sum;
        }
        while(x-1>=0&&!a[x-1][y])
        {
            a[--x][y]=++sum;
        }
        while(y+1<n&&!a[x][y+1])
        {
            a[x][++y]=++sum;
        }
    }
    for(x=0;x<n;x++){
        for(y=0;y<n;y++){
            printf("%3d",a[x][y]);
        }
        printf("\n");
    }
    return 0;
}


 

Released seven original articles · won praise 0 · Views 110

Guess you like

Origin blog.csdn.net/qq_44954571/article/details/103979045