C + + recursive implementation of spiral array instance code

Time:2021-2-23

For reference only, if there is room for improvement, welcome to exchange!

#include<iostream>
using namespace std;
//The parameter x is the subscript of the starting element, and m and N are used to determine the end of the four edges.
//a. B is used to judge whether the spiral can be carried out. P is a two-dimensional array.
void lx(int x,int m, int n, int a, int b, int **p);
int main()
{
  //Input row and column
 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;
 //Call LX function
 lx(0,m,n,m,n,a);
 //Output helix array
  for (int i = 0; i < m; ++i)
 {
 for (int j = 0; j < n; ++j)
  cout << a[i][j] << ' ';
 cout << endl;
 }
 //Don't forget to delete dynamic memory
 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)
{
//If x is not 0, the value of the first element is the value of the previous element plus one.
 if (x)
 p[x][x] = p[x][x - 1] + 1;
//Complete the assignment of four edges
 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;
//Determine whether the spiral condition is met, so as to determine whether to call LX function
 if ((a - 2 > 0) && (b - 2 > 0))
 lx(x + 1,m - 1, n - 1,a-2,b-2, p);
 
}

debugging

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

Knowledge point expansion:

Recursive implementation of helix number in 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);
 }
 }
}

summary

So far, this article about C + + recursive spiral array is introduced here. For more information about C + + recursive spiral array, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!