时间:2020-12-20 12:35:08 | 栏目:C代码 | 点击:次
仅供参考,若有可改进之处,欢迎一起交流!
#include<iostream> using namespace std; //参数x表示开始元素的下标,m,n用于确定4条边尽头。 //a,b则用于判断是否可进行螺旋。p为二维数组。 void lx(int x,int m, int n, int a, int b, int **p); int main() { //输入行列 int m = 0, n = 0; cin >> m >> n; int **a = new int*[m]; for (int i = 0; i < m; ++i) a[i] = new int[n]; a[0][0] = 1; //调用lx函数 lx(0,m,n,m,n,a); //输出螺旋数组 for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) cout << a[i][j] << ' '; cout << endl; } //别忘了删动态内存 for (int i = 0; i < m; ++i) delete []a[i]; delete[]a; } void lx(int x ,int m, int n,int a,int b,int **p) { //如果x不为0,则首元素的值为前一个元素值加一。 if (x) p[x][x] = p[x][x - 1] + 1; //完成四条边的赋值 for (int i = x+1; i < n; ++i) p[x][i] = p[x][i - 1] + 1; for (int j = x+1; j < m; ++j) p[j][n - 1] = p[j - 1][n - 1] + 1; if(a>1) for (int i = n - 2; i >= x; --i) p[m - 1][i] = p[m - 1][i + 1] + 1; if(b>1) for (int j = m - 2; j >= x+1; --j) p[j][x] = p[j + 1][x] + 1; //判断是否符合螺旋条件,从而判断是否调用lx函数 if ((a - 2 > 0) && (b - 2 > 0)) lx(x + 1,m - 1, n - 1,a-2,b-2, p); }
调试
7 8
1 2 3 4 5 6 7 8
26 27 28 29 30 31 32 9
25 44 45 46 47 48 33 10
24 43 54 55 56 49 34 11
23 42 53 52 51 50 35 12
22 41 40 39 38 37 36 13
21 20 19 18 17 16 15 14
知识点扩展:
c++ 螺旋数递归实现
void printValue(int head,int x,int y,int n) { int NextHead = head + 4*n -4; head = head -1; if(x==n) { cout << (n+y-1)+head <<" "; if(!head) cout<<endl; } else if(y == 1) { cout<< x + head<<" "; } else if(x==1) { cout << (4*n-2)-y +head<< " "; } else if(y==n) { cout << 3*n-1-x + head << " "; } else { printValue(NextHead,x-1,y-1,n-2); } } void SpiralNumber(int n) { for (int y = 1;y<=n;y++) { for (int x = 1;x<=n;x++) { printValue(1,x,y,n); } } }
总结