蛇形填数 ------- 模拟水题

在n*n的方阵里填入 1,2,3,4 ,.....n*n ,要求填入蛇形,例如 n=4时的方阵为

10  11  12   1

9   16   13   2

8   15   14   3

7    6     5    4

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <math.h>
#define MAXN 10
int main()
{
    int n,a[MAXN][MAXN],i,j,x,y;
    scanf("%d",&n);
    memset(a,0,sizeof(a));    //0电表关着的
    int tot=0;
    tot=a[x=0][y=n-1]=1;
    while(tot<n*n){
        while(x+1<n&&!a[x+1][y])   a[++x][y]=++tot;
        while(y-1>=0&&!a[x][y-1])   a[x][--y]=++tot;
        while(x-1>=0&&!a[x-1][y])   a[--x][y]=++tot;
        while(y+1<n && !a[x][y+1])  a[x][++y]=++tot;
    }

    for(i=0;i<n;i++){
        for(j=0;j<n;j++)
         printf("%3d ",a[i][j]);
    printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wintersong/p/5041870.html