1. 程式人生 > >蛇形填數 (一)

蛇形填數 (一)

蛇形填數

時間限制:3000 ms  |  記憶體限制:65535 KB 難度:3
描述
在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 1
6 9 2

5 4 3

#include<iostream>
#include<string.h>
using namespace std;
#define MAX 100
int a[MAX][MAX];
int main(void){
	int n,x,y,count;
	cin>>n;
	memset(a,0,sizeof(a));
	count=a[x=0][y=n-1]=1;
	while(count<n*n){
		while(x+1<n && !a[x+1][y])a[++x][y]=++count;
		while(y-1>=0&& !a[x][y-1])a[x][--y]=++count;
		while(x-1>=0&& !a[x-1][y])a[--x][y]=++count;
		while(y+1<n && !a[x][y+1])a[x][++y]=++count;
	}
	for(int i=0;i<n;i++)
	  for(int j=0;j<n;j++){
	  	cout<<a[i][j]<<"  ";
	  	if(j==n-1)
	  	cout<<endl;
	  }
}