题目:
1 打印如下形式的矩阵;
n=5:
1 2 9 10 25
4 3 8 11 24
5 6 7 12 23
16 15 14 13 22
17 18 19 20 21
n=6:
1 2 9 10 25 26
4 3 8 11 24 27
5 6 7 12 23 28
16 15 14 13 22 29
17 18 19 20 21 30
36 35 34 33 32 31
分析:可以看出有这样的规律 --- 按right, down, left, down, right, up这样的路线跌增,并且只有在left,up时可能完成打印。
方法:按照这个规律先生成数组,然后再打印
#define N 9
void PrintMatrix()
{
int row=2, colum=2,n=1;
int i=1, j=0;
int p[N+1][N+1];
int ix;
while (1)
{
//right
while(j<colum)
p[i][++j]=n++;
colum++;
//down
while(i<row)
p[++i][j] = n++;
row++;
//left
while(j>1)
p[i][--j] = n++;
if (row > N)
break;
//down
while(i<row)
p[++i][j] = n++;
row++;
//right
while(j<colum)
p[i][++j] = n++;
colum++;
//up
while(i>1)
p[--i][j] = n++;
if (colum > N)
break;
}
for (i=1; i<=N; i++)
{
for (j=1; j<=N; j++)
printf("%2d ", p[i][j]);
printf("\n");
}
}
n=9:
1 2 9 10 25 26 49 50 81
4 3 8 11 24 27 48 51 80
5 6 7 12 23 28 47 52 79
16 15 14 13 22 29 46 53 78
17 18 19 20 21 30 45 54 77
36 35 34 33 32 31 44 55 76
37 38 39 40 41 42 43 56 75
64 63 62 61 60 59 58 57 74
65 66 67 68 69 70 71 72 73