螺旋方阵
如何用c语言输出一个螺旋方阵,新手,尽量简单点,带点解释更好,麻烦大家了程序代码:
#include"stdafx.h" #include <stdio.h> #define N 100 int Matrix[N][N] = {0}; enum direction{top, bottom, left, right};//螺旋着跑的方向 void printMatrix(int n){ //打印方阵 for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ printf("%d\t", Matrix[i][j]); } printf("\n"); } } bool isOver(int i, int j, int n){ //是否符合结束条件 bool tag = true; if(j < n-1 && Matrix[i][j + 1] ==0) tag = false; if(j > 0 && Matrix[i][j - 1] ==0) tag = false; if(i < n-1 && Matrix[i + 1][j] ==0) tag = false; if(i > 0 && Matrix[i - 1][j] ==0) tag = false; return tag; } void logicalOperation(int n){ //对方阵逻辑操作 direction flag = right; int i = 0, j = 0, data = 1; while(true){ Matrix[i][j] = data; switch(flag){ case right: { if(j == n - 1 || Matrix[i][j + 1] != 0){ i++; flag = bottom; } else j++; } break; case bottom: { if(i == n - 1 || Matrix[i + 1][j] != 0){ j--; flag = left; } else i++; } break; case left: { if(j == 0 || Matrix[i][j - 1] != 0){ i--; flag = top; } else j--; } break; case top: { if(i == 0 || Matrix[i - 1][j] != 0){ j++; flag = right; } else i--; } break; default: break; } data++; if(isOver(i, j, n)){ Matrix[i][j] = data; break; } } } int main() { int n; //n阶方阵 printf("input N:"); scanf("%d", &n); getchar(); if(n < 1 || n > 100){ printf("envalid number!\n"); return 0; } logicalOperation(n); printMatrix(n); return 0; }
就根据螺旋方阵的规律来写的,从外面往里面转,一个个给数据,笨方法,还没想到更好的
[此贴子已经被作者于2017-4-10 17:02编辑过]