蛇形填数

来源:互联网 发布:淘宝全屏代码 编辑:程序博客网 时间:2024/06/04 17:43

题目描述

在n*n方阵里填入1,2,...,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4

输入

直接输入方阵的维数,即n的值。(n<=100)

输出

输出结果是蛇形方阵。

样例输入

3

样例输出

7 8 16 9 25 4 3

#include<stdio.h>int num[250][250];int book[250][250];int main(){    int n;    scanf("%d",&n);    int cnt=1,i=0,j=n-1;    num[i][j]=1;    book[i][j]=1;    while(cnt<n*n){        while(i+1<n&&!book[i+1][j]){     //向下            book[i+1][j]=1;            num[++i][j]=++cnt;        }        while(j-1>=0&&!book[i][j-1]){   //向左            book[i][j-1]=1;            num[i][--j]=++cnt;        }        while(i-1>=0&&!book[i-1][j]){  //向上            book[i-1][j]=1;            num[--i][j]=++cnt;        }        while(j+1<n&&!book[i][j+1]){   //向右            book[i][j+1]=1;            num[i][++j]=++cnt;        }    }    for(i=0;i<n;i++){        for(j=0;j<n-1;j++)            printf("%d ",num[i][j]);        printf("%d\n",num[i][j]);    }return 0;}