蛇形填數
- 在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 1 6 9 2 5 4 3
代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int n;
int a[105][105];
memset(a,0,sizeof(a)); //將數組的值都賦值爲0
cin>>n;
int x=0,y=n-1; //對應數組行列
int s=n*n,d=a[x][y]=1;
while(d<s) //總共有s=n*n個數,在d==s時循環結束
{
while(x<n-1 && !a[x+1][y]) //向下 ,!a[x+1][y]代表a[x+1][y]==0時循環
a[++x][y]=++d;
while(y>0 && !a[x][y-1]) //向左
a[x][--y]=++d;
while(x>0 && !a[x-1][y]) //向上
a[--x][y]=++d;
while(y<n-1 && !a[x][y+1]) //向右
a[x][++y]=++d;
}
for(x=0;x<n;x++)
{
for(y=0;y<n;y++)
cout<<a[x][y]<<" ";
cout<<endl;
}
return 0;
}