首页 > 代码库 > nyOJ基础题:蛇形填数

nyOJ基础题:蛇形填数

一遍AC#include <stdio.h>/*描述在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:10 11 12 19 16 13 28 15 14 37 6 5 4输入直接输入方陈的维数,即n的值。(n<=100)输出输出结果是蛇形方陈。样例输入3样例输出7 8 16 9 25 4 3*/int main(){    int n;    while(~scanf("%d", &n)){        int a[n][n];        for(int i = 0; i < n; i++)            for(int j = 0; j < n; j++)                a[i][j] = 0;        int x, y, number;//循环变量+计数的number        //预处理,填外圈        a[0][n-1] = 1;        for(y = 0, number = 1; y < n; y++) a[y][n-1] = number++;        for(x = n-2; x >= 0; x--) a[n-1][x] = number++;        for(y = n-2; y >= 0; y--) a[y][0] = number++;        for(x = 1; x <= n-2; x++) a[0][x] = number++;        x = 0, y = n-2;        while(number <= n*n){            //south 从a[0][n-2]开始            //printf("%d~~~\n", a[x][y]);            while((number <= (n*n)) && !a[x+1][y]) a[++x][y] = number++;            //west            while((number <= n*n) && !a[x][y-1]) a[x][--y] = number++;            //north            while((number <= n*n) && !a[x-1][y]) a[--x][y] = number++;            //east            while((number <= n*n) && !a[x][y+1]) a[x][++y] = number++;        }        //输出        for(int i = 0; i < n; i++){            for(int j = 0; j < n; j++){                if(j==0) printf("%d", a[i][j]);                else printf(" %d", a[i][j]);            }            puts("");        }    }    return 0;}

  

nyOJ基础题:蛇形填数