C++ recursive implementation of spiral array instance code

  • 2020-08-22 22:20:06
  • OfStack

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


#include<iostream>
using namespace std;
// parameter x The index of the starting element, m,n Used to determine the 4 The end of the edge. 
//a,b Is used to determine whether the helix can be performed. p for 2 Dimensional array. 
void lx(int x,int m, int n, int a, int b, int **p);
int main()
{
  // Enter the ranks of 
 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 spiral 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 Don't for 0 , the value of the first element is front 1 Plus the number of elements 1 . 
 if (x)
 p[x][x] = p[x][x - 1] + 1;
// complete 4 An assignment of 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;
// Determines whether the helix condition is met and therefore 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:

c++ spiral number recursive implementation


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);
 }
 }
}

conclusion


Related articles: