Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print n x n spiral matrix using O(1) extra space in C Program.
We are given a positive integer n and need to create a spiral matrix of n x n using only O(1) extra space in clockwise direction. A spiral matrix starts from the center and fills values in a spiral pattern outward.
The spiral matrix fills values in clockwise direction starting from the center. For example, a 3x3 matrix would fill as: center → right → down → left → up and so on.
Syntax
void spiralMatrix(int n);
Algorithm
The key insight is to divide the matrix into upper-right and lower-left halves using mathematical formulas −
- For upper right half: mat[i][j] = 2 * ((n-2*x)*(n-2*x) - (i-x) - (j-x))
- For lower left half: mat[i][j] = 2 * ((n-2*x-2)*(n-2*x-2) + (i-x) + (j-x))
Where x represents the layer in which element (i,j) exists.
Example
#include <stdio.h>
// Function to generate n x n spiral matrix
void spiralMatrix(int n) {
int i, j, a, b, x;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
// Find minimum of four inputs to determine layer
a = (i < j) ? i : j;
b = (n-1-i) < (n-1-j) ? (n-1-i) : (n-1-j);
x = a < b ? a : b;
// For upper right half
if (i <= j) {
printf("%d\t", 2 * ((n-2*x)*(n-2*x) - (i-x) - (j-x)));
}
// For lower left half
else {
printf("%d\t", 2 * ((n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)));
}
}
printf("
");
}
}
int main() {
int n = 3;
printf("Spiral matrix of size %dx%d:
", n, n);
spiralMatrix(n);
return 0;
}
Spiral matrix of size 3x3: 18 16 14 4 2 12 6 8 10
How It Works
- Calculate layer number x for each position (i,j)
- Determine if position is in upper-right or lower-left half
- Apply appropriate formula based on position
- Use only constant extra space O(1)
Conclusion
This approach efficiently generates a spiral matrix using mathematical formulas without requiring extra space for storage. The algorithm runs in O(n²) time with O(1) space complexity, making it memory-efficient for large matrices.
