Fill in the N * n square matrix with 1, 2,..., n * n, which must be filled into a snake. For example, when n = 4, the square matrix is:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
In the square matrix above, extra spaces are only used to facilitate the observation of the law and do not need to be output strictly.
N ≤ 8.
Analysis:
Define a two-dimensional array to store the square matrix, First Bottom, until it cannot be filled, then left,
Next is the top, and finally the right.
Code:
#include<stdio.h>#include<string.h>#define MAXN 10int a[MAXN][MAXN];int main(){ int n,x,y,t; t=0; while(~scanf("%d",&n)) { memset(a,0,sizeof(a)); t=a[x=0][y=n-1]=1; while(t<n*n) { while(x+1<n&&!a[x+1][y]) a[++x][y]=++t; while(y-1>=0&&!a[x][y-1]) a[x][--y]=++t; while(x-1>=0&&!a[x-1][y]) a[--x][y]=++t; while(y+1<n&&!a[x][y+1]) a[x][++y]=++t; } for(x=0;x<n;x++) { for(y=0;y<n;y++) printf("%3d",a[x][y]); printf("\n"); } } return 0;}