code.club
標題:
蛇型陣列的寫法
[打印本頁]
作者:
enter
時間:
2015-10-16 15:10
標題:
蛇型陣列的寫法
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main(){
int n,i,j,sum=0;
cin>>n;
int a[n][n];
memset(a,0,sizeof(a));
sum=a[i=0][j=n-1]=1;
while(sum<n*n)
{
while((i+1<n)&&!a[i+1][j]) a[++i][j]= ++sum;
while((j-1>=0)&&!a[i][j-1]) a[i][--j] = ++sum;
while((i-1>=0)&&!a[i-1][j]) a[--i][j] = ++sum;
while((j+1<n)&&!a[i][j+1]) a[i][++j] = ++sum;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++) printf("%3d ",a[i][j]);
cout<<endl;
}
return 0;
}
19 20 21 22 23 24 1
18 37 38 39 40 25 2
17 36 47 48 41 26 3
16 35 46 49 42 27 4
15 34 45 44 43 28 5
14 33 32 31 30 29 6
13 12 11 10 9 8 7
歡迎光臨 code.club (https://code.club/)
Powered by Discuz! X3.2