/*螺旋矩阵*/
#include <stdio.h>
#include <conio.h>
#define DOWN 0
#define LEFT 1
#define UP 2
#define RIGHT 3
//N*N矩阵
#define N 5
void printMatrix(int *a[], int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%4d", a[i][j]);
}
printf("\n");
}
}
void spiralMatrix(int *a[], int n) {
int i, j; //坐标
int count; //计数器
int k; //循环变量
int direct; //方向指示
i = 0;
j = --n;
count = 0;
direct = DOWN;
while (n > 0) {
for (k = 0; k < n; k++) {
a[i][j] = count++;
switch (direct) {
case DOWN:
i++;
break;
case LEFT:
j--;
break;
case UP:
i--;
break;
case RIGHT:
j++;
break;
}
}
//如果刚走过的方向为RIGHT, 步长减2, 并校正位置
if (direct == RIGHT) {
i++;
j--;
n -= 2;
}
//换方向
direct = (direct + 1) % 4;
}
if (n == 0) {
a[i][j] = count;
}
}
void main(void) {
int m[N][N] = {0};
int *a[N];
int i;
for (i = 0; i < N; i++) {
a[i] = m[i];
}
spiralMatrix(a, N);
printMatrix(a, N);
printf("按任意键退出...");
getch();
}
本文地址:http://com.8s8s.com/it/it25446.htm