看到一個迴旋數組的程序,留待以後分析。
/*
迴旋數組:
[root@bogon home]# gcc -g -o q1 q1.c
[root@bogon home]# ./q1
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
*/
#include <stdio.h>
void spin() //迴旋數組
{
int matrix[10][10];
int col,row,dir;
col=0;
row=0;
int rotatenum=10; //迴旋標準數,當curnum與其相等時,就反生轉向
int curnum=0;
dir=1;//1->右,2下,3左,4上
int i, p, q;
for (i=1;i<10*10+1;i++)
{
matrix[row][col]=i;
curnum++;
switch(dir)
{
case 1:
if(curnum==rotatenum)
{
row++;
rotatenum--;
dir=2;
curnum=0;
}
else
col++;
break;
case 2:
if (curnum==rotatenum)
{
col--;
dir=3;
curnum=0;
}
else
row++;
break;
case 3:
if (curnum==rotatenum)
{
row--;
dir=4;
curnum=0;
rotatenum--;
}
else
col--;
break;
case 4:
if (curnum==rotatenum)
{
col++;
dir=1;
curnum=0;
}
else
row--;
break;
}
}
for (p=0;p<10;p++)
{
for (q=0;q<10;q++)
{
printf("%-3d ",matrix[p][q]);
}
printf("\n");
}
}
void main()
{
spin();
}
再補充一個厲害的:
#include <stdio.h>
#define MAXN 10
char m[MAXN+2][MAXN+2];
char d;
int x,y,k,n;
void main() {
while (1) {
printf("Input n(1..%d):",MAXN);
fflush(stdout);
rewind(stdin);
if (1==scanf("%d",&n)) {
if (1<=n && n<=MAXN) break;
}
}
y=0 ;for (x=0;x<=n+1;x++) m[y][x]=1;
y=n+1;for (x=0;x<=n+1;x++) m[y][x]=1;
x=0 ;for (y=0;y<=n+1;y++) m[y][x]=1;
x=n+1;for (y=0;y<=n+1;y++) m[y][x]=1;
for (y=1;y<=n;y++) {
for (x=1;x<=n;x++) {
m[y][x]=0;
}
}
x=1;
y=1;
k=0;
d='D';
while (1) {
k++;
if (k>n*n) break;
m[y][x]=k;
switch (d) {
case 'D':
if (0==m[y+1][x]) y++;
else {x++;d='R';}
break;
case 'R':
if (0==m[y][x+1]) x++;
else {y--;d='U';}
break;
case 'U':
if (0==m[y-1][x]) y--;
else {x--;d='L';}
break;
case 'L':
if (0==m[y][x-1]) x--;
else {y++;d='D';}
break;
}
}
for (y=1;y<=n;y++) {
for (x=1;x<=n;x++) {
printf("%4d",m[y][x]);
}
printf("\n");
}
}
執行效果如下: 留待以後分析[root@bogon home]# gcc -g -o q2 q2.c
[root@bogon home]# ./q2
Input n(1..10):9
1 32 31 30 29 28 27 26 25
2 33 56 55 54 53 52 51 24
3 34 57 72 71 70 69 50 23
4 35 58 73 80 79 68 49 22
5 36 59 74 81 78 67 48 21
6 37 60 75 76 77 66 47 20
7 38 61 62 63 64 65 46 19
8 39 40 41 42 43 44 45 18
9 10 11 12 13 14 15 16 17
[root@bogon home]# ./q2
Input n(1..10):2
1 4
2 3
[root@bogon home]# ./q2
Input n(1..10):11
Input n(1..10):10
1 36 35 34 33 32 31 30 29 28
2 37 64 63 62 61 60 59 58 27
3 38 65 84 83 82 81 80 57 26
4 39 66 85 96 95 94 79 56 25
5 40 67 86 97 100 93 78 55 24
6 41 68 87 98 99 92 77 54 23
7 42 69 88 89 90 91 76 53 22
8 43 70 71 72 73 74 75 52 21
9 44 45 46 47 48 49 50 51 20
10 11 12 13 14 15 16 17 18 19
[root@bogon home]# ./q2
Input n(1..10):5
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9