A Wonderful Recursion I want to Share!!

Revision en17, by salehin_076923, 2025-06-16 20:54:44

While solving Skibidi Table problem, (problem link: https://mirror.codeforces.com/contest/2093/problem/D ) I was wondering How to Generate the Pattern->

Number of Rows: $$$2^n$$$

Number of Columns: $$$2^n$$$

Number of Cells: $$$2^{2n}$$$

$$$n=1:$$$

1  4

3  2

$$$n=2:$$$

1   4   13  16 

3   2   15  14 

9   12  5   8 

11  10  7   6

$$$n=3:$$$

1   4    13   16  49  52  61  64 

3   2    15   14  51  50  63  62 

9   12   5    8   57  60  53  56 

11  10   7    6   59  58  55  54 

33  36   45   48  17  20  29  32 

35  34   47   46  19  18  31  30 

41  44   37   40  25  28  21  24 

43  42   39   38  27  26  23  22

And so on......

An idea of implementing it by Recursion came to my mind Alhamdulillah!

As for each case, we are first entering the $$$1st$$$ cell, then the $$$4th$$$ cell, then the $$$3rd$$$ cell, then $$$2nd$$$ cell. Recursively calling it, we can store the pattern in an array & print it to get the pattern!

Code:

#include<bits/stdc++.h>
using namespace std;

const int n=1000;
int arr[n][n];

void fillArray(int x,int y,int p,int val){
	if(p==1){
		arr[x][y]=val;
		return;
	}

	fillArray(x,y,p/2,val);
	fillArray(x+p/2,y+p/2,p/2,val+p*p/4);
	fillArray(x+p/2,y,p/2,val+2*p*p/4);
	fillArray(x,y+p/2,p/2,val+3*p*p/4);
}

int main(){
	int n;
	cin>>n;
	int p=pow(2,n);
	fillArray(0,0,p,1);
	for(int i=0;i<p;i++){
		for(int j=0;j<p;j++){
			cout<<arr[i][j]<<" ";
		}
		cout<<endl;
	}
}

You can check it by running the code!!!

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en17 English salehin_076923 2025-06-16 20:54:44 0 (published)
en16 English salehin_076923 2025-06-16 20:53:32 6
en15 English salehin_076923 2025-06-16 20:52:34 631
en14 English salehin_076923 2025-06-16 20:49:45 8 Tiny change: 'n\n\n$1$ $4$ \n\n' -> 'n\n\n$1$ $4$ \n\n'
en13 English salehin_076923 2025-06-16 20:48:55 54
en12 English salehin_076923 2025-06-16 20:46:33 18
en11 English salehin_076923 2025-06-16 20:45:17 82
en10 English salehin_076923 2025-06-16 20:43:22 390
en9 English salehin_076923 2025-06-16 20:36:59 21
en8 English salehin_076923 2025-06-16 20:35:29 4
en7 English salehin_076923 2025-06-16 20:35:10 2 Tiny change: '\n\nn=1:\n```\n1 4' -> '\n\nn=1:\n\n```\n1 4'
en6 English salehin_076923 2025-06-16 20:34:42 28 Tiny change: 'rsion.png)' -> 'rsion.png)\n\n[Link](http://mirror.codeforces.com/7ccf9d/Recursion.png)'
en5 English salehin_076923 2025-06-16 20:34:09 421 Tiny change: 'rsion.png)' -> 'rsion.png)\n\n[Link](http://mirror.codeforces.com/7ccf9d/Recursion.png)'
en4 English salehin_076923 2025-06-16 20:31:31 54 Tiny change: 'rsion.png)' -> 'rsion.png)\n\n[Link](http://mirror.codeforces.com/7ccf9d/Recursion.png)'
en3 English salehin_076923 2025-06-16 20:30:19 162
en2 English salehin_076923 2025-06-16 20:22:43 60
en1 English salehin_076923 2025-06-16 20:19:14 106 Initial revision (saved to drafts)