Design the pattern as represented in the famous snake and ladders game. Your task is to print the pattern as represented in snake and ladders game for a given integer input N, where N denotes the number of rows and columns of the pattern array. Note: N given will be always even.
Examples:
Input: N=4 Output: 7 8 9 6 5 4 1 2 3 Input: N = 10 Output: 100 99 98 97 96 95 94 93 92 91 81 82 83 84 85 86 87 88 89 90 80 79 78 77 76 75 74 73 72 71 61 62 63 64 65 66 67 68 69 70 60 59 58 57 56 55 54 53 52 51 41 42 43 44 45 46 47 48 49 50 40 39 38 37 36 35 34 33 32 31 21 22 23 24 25 26 27 28 29 30 20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10
Approach: These type of pattern problems can be solved easily by using loops with some condition that fits correctly for placing the ith element at its correct position.
To solve this problem:
(1) Make a 2D array of NxN size and run a nested loop from i=0 to n (representing the number of rows) and from j=0 to n (representing the number of columns) respectively.
(2) Then check if the row is odd indexed i.e.:
if i%2!=0 : then store the elements in descending order from left to right.
else: store the elements in the array in ascending order form left to right.
(3) Print the ans array you have created.
Implementation in C++ –
//C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
void printPattern(int n){
//creating a 2D array
int a[n][n];
//iterate i from 0 to n-1
for(int i = 0; i < n; i++)
{
//iterate j from 0 to n-1
for(int j = 0; j < n; j++)
{
if(i % 2 != 0) //if i is odd
a[i][n-1-j] = n*(n-i)-j;
else // check if i is even
a[i][j] = n*(n-i)-j;
}
}
//print the ans array
for(int i = 0; i < n; i++)
{
for(int j = 0; j<n; j++){
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
}
//Driver code
int main()
{
//Given input
int n=10;
// Funtion call
printPattern(n);
return 0;
}
Output:
100 99 98 97 96 95 94 93 92 91 81 82 83 84 85 86 87 88 89 90 80 79 78 77 76 75 74 73 72 71 61 62 63 64 65 66 67 68 69 70 60 59 58 57 56 55 54 53 52 51 41 42 43 44 45 46 47 48 49 50 40 39 38 37 36 35 34 33 32 31 21 22 23 24 25 26 27 28 29 30 20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10
Time Complexity: O(N ^2)
Auxiliary Space: O(N ^2)
