关于数组的题~
我刚接触数组,偶尔看到的题,请高手多提供几种方法~C语言或C++方法都行~1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
谢谢了!!
谢谢了!!
2010-04-22 22:38
2010-04-23 10:13
2010-04-23 13:05
程序代码:#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a;
int i,j;
int n=1,row,direction;
printf("Input the number of rows:");
scanf("%d",&row);
//set matrix
a = (int **)malloc((row+2)*sizeof(int *));
for (i=0;i<row+2 ;i++ )
a[i]=(int *)calloc(row+2,sizeof(int));
//initail wall
for (i=0;i<row+2 ;i++ )
{
a[i][0]=1;
a[0][i]=1;
a[i][row+1]=1;
a[row+1][i]=1;
}
i=1;
j=1;
a[1][1]=1;
direction=1; /* 1 right,2 down,3 left, 4 up */
while(n<row*row)
{
if (direction==1)
{
if (a[i][j+1]!=0)
{
direction=2;
continue;
}
a[i][++j] = ++n;
}
else if(direction==2)
{
if (a[i+1][j]!=0)
{
direction=3;
continue;
}
a[++i][j] = ++n;
}
else if(direction==3)
{
if (a[i][j-1]!=0)
{
direction=4;
continue;
}
a[i][--j] = ++n;
}
else
{
if (a[i-1][j]!=0)
{
direction=1;
continue;
}
a[--i][j] = ++n;
}
}
//printf
for (i=1;i<=row ;i++ )
{
for (j=1;j<=row ;j++ )
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}

2010-04-23 16:49
程序代码:#include<stdio.h>
int main(void)
{
int i,x,j,y,n,a[20][20],k;
printf("input :");
scanf("%d",&n);
for (i=0,y=0,k=1;i<n;i++)
{
x=i;
while (x<n-i)a[x++][y]=k++;x--;k--;
while (y<n-i)a[x][y++]=k++;y--;k--;
while (x+1>i)a[x--][y]=k++;x++;k--;
while (y>i)a[x][y--]=k++;y++;
}
printf("\n");
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
printf("%6d",a[j][i]);
printf("\n");
}
return 0;
}

2010-04-23 18:31
2010-04-26 23:48
2010-04-27 07:10
2010-04-27 09:43
2010-04-27 19:11
2010-04-29 22:44