求蛇形输入方阵
例如:N=4
7 13 14 16
6 8 12 15
2 5 9 11
1 3 4 10
#include<stdio.h>
int main()
{
int i,j,k,count,temp,N,n;
printf("please input N");
scanf("%d",&N);
n=N-1;count=1;k=1;j=0;i=n;
int a[N][N];
while(count<=N)
{
for(temp=0;temp<count;temp++)
{
if(count%2!=0)
{
a[i--][j--]=k++;
if(j<0)
{
j=0;
continue;
}
}
if(count%2==0)
{
a[i++][j++]=k++;
if(i>n)
{
i=n;
continue;
}
}
}
count++;
}
j=n-1;j=n;count=1;
while(count<N)
{
for(temp=0;temp<N-count;temp++)
{
if(count%2!=0)
{
a[i--][j--]=k++;
if(i<0)
{
i=0;j+=2;
continue;
}
}
if(count%2==0)
{
a[i++][j++]=k++;
if(i>n)
{
j=n;i-=2;
continue;
}
}
}
count++;
}
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
主要是弄完一个角之后,再另一个角的起点判断有问题
#include<stdio.h>
int main()
{
int i, j, k, count, temp, N, n;
printf("please input N");
scanf("%d", &N);
n = N - 1; count = 1; k = 1; j = 0; i = n;
int a[10][10];
while (count <= N)
{
for (temp = 0; temp < count; temp++)
{
if (count % 2 != 0)
{
a[i--][j--] = k++;
if (i < 0)
i = 0;
if (j < 0)
j = 0;
}
else if (count % 2 == 0)
{
a[i++][j++] = k++;
if (i > n)
i = n;
if (j > n)
j = n;
}
}
count++;
}
if (N % 2 != 0) //输入完一个角之后,起点跟N的奇偶有关
j++;
else
i--;
count = 1;
while (count < N)
{
for (temp = 0; temp < N - count; temp++)
{
if ((N-count) % 2 != 0)
{
a[i--][j--] = k++;
if (i < 0) {
i = 0;
j += 2;
}
}
if ((N-count) % 2 == 0)
{
a[i++][j++] = k++;
if (j > n) {
j = n;
i -= 2;
}
}
}
count++;
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
printf("%3d ", a[i][j]); //设置宽度为3
printf("\n");
} return 0;
}