自定义螺旋矩阵的阶长N,并将螺旋方阵存放到N×N的二维数组中并把它打印输出。注:请尊重个人劳动成果,转载请注明出处。
其实现代码如下:
/************************************************************************ * 文件名 : HelixMatrix.c * * 创建日期: 2012-8-15 * * 作者 : Martin(p11234) * * 联系方式: Ma.Martin153@gmail.com * * 描述 : 自定义螺旋矩阵的阶长N,并将螺旋方阵存放到 * * N×N的二维数组中并把它打印输出。 * * 修改 : 无 * * * * 声明 : 本程序仅供学习交流,未经作者授权不得用于商业目的, * * 否则保留追究法律责任的权利。 * *************************************************************************/ #include <stdio.h> // 自定义的螺旋矩阵的阶 #define N 5 int main(void) { int index; // 临时计数单元 int MaxIndex; // 临时计数单元的上界 int tempRow; // 临时列计数单元 int tempLine; // 临时行计数单元 int MaxTemp; // 临时行列计数单元的上界 int tempShowLine; // 用于显示螺旋矩阵的临时行计数单元 int tempShowRow; // 用于显示螺旋矩阵的临时列计数单元 int number= 0; // 累加器 int Matrix[N][N] = {0}; // 保存螺旋矩阵的二维数组 MaxIndex = ((N + 1) / 2 - 1); // 转圈循环,为数组赋值 for (index = 0; index <= MaxIndex; index++) { tempRow = index; tempLine = index; MaxTemp = N - (index * 2 + 1) + index; // 左竖循环 for (; tempRow < MaxTemp; tempRow++) { Matrix[tempRow][tempLine] = (++number); } // 下横循环 for (; tempLine < MaxTemp; tempLine++) { Matrix[tempRow][tempLine] = (++number); } // 右竖循环 for (; tempRow > index; tempRow--) { Matrix[tempRow][tempLine] = (++number); } // 上横循环 for (; tempLine > index; tempLine--) { Matrix[tempRow][tempLine] = (++number); } } // 如果 N 为奇数 if (1 == N % 2) { Matrix[tempRow][tempLine] = (++number); } else { ; } // 显示螺旋矩阵 printf("%d阶螺旋矩阵如下所示:\n", N); for (tempShowRow = 0; tempShowRow < N; tempShowRow++) { for (tempShowLine = 0; tempShowLine < N; tempShowLine++) { printf("%-6d", Matrix[tempShowRow][tempShowLine]); } printf("\n\n"); } return 0; }
当螺旋矩阵的阶数是5时,其效果图如下所示: