Print N*N spiral matrix:
Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space.
Input: n = 5 Output: 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17
CODE:
// C++ program to print a n x n spiral matrix
// in clockwise direction using O(1) space
#include <bits/stdc++.h>
using namespace std;
// Prints spiral matrix of size n x n containing
// numbers from 1 to n x n
void
printSpiral(
int
n)
{
for
(
int
i = 0; i < n; i++)
{
for
(
int
j = 0; j < n; j++)
{
// x stores the layer in which (i, j)th
// element lies
int
x;
// Finds minimum of four inputs
x = min(min(i, j), min(n-1-i, n-1-j));
// For upper right half
if
(i <= j)
printf
(
"%2d "
, (n-2*x)*(n-2*x) - (i-x)
- (j-x));
// for lower left half
else
printf
(
"%2d "
, (n-2*x-2)*(n-2*x-2) + (i-x)
+ (j-x));
}
printf
(
"\n"
);
}
}
// Driver code int main() { int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0; } //credits: geeksforgeeks
#include
ReplyDelete//#define min(i,j) (i<j?i:j)
//you can use #define or below min function. both will yield the same result.
int min(int x,int y)
return x<y?x:y;
void printSpiral(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int x;
// Finds minimum of four inputs
x = min(min(i, j), min(n-1-i, n-1-j));
// For upper right half
if (i <= j)
printf("%2d ", (n-2*x)*(n-2*x) - (i-x)
- (j-x));
// for lower left half
else
printf("%2d ", (n-2*x-2)*(n-2*x-2) + (i-x)+ (j-x));
}
printf("\n");
}
}
// Driver code
int main()
{
int n = 4;
// print a n x n spiral matrix in O(1) space
printSpiral(n);
return 0;
}