#include <stdio.h>
#include <stdlib.h>
int** generateSpiralMatrix(int n) {
int** matrix = malloc(n * sizeof(int*));
for (int i = 0; i < n; i++) {
matrix[i] = malloc(n * sizeof(int));
}
int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
// Fill top row
for (int i = left; i <= right; ++i)
matrix[top][i] = num++;
top++;
// Fill right column
for (int i = top; i <= bottom; ++i)
matrix[i][right] = num++;
right--;
// Fill bottom row
if (top <= bottom) {
for (int i = right; i >= left; --i)
matrix[bottom][i] = num++;
bottom--;
}
// Fill left column
if (left <= right) {
for (int i = bottom; i >= top; --i)
matrix[i][left] = num++;
left++;
}
}
return matrix;
}
void freeMatrix(int** matrix, int n) {
for (int i = 0; i < n; i++)
free(matrix[i]);
free(matrix);
}
int main() {
int n = 3; // size of the matrix
int** spiralMatrix = generateSpiralMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", spiralMatrix[i][j]);
}
printf("\n");
}
freeMatrix(spiralMatrix, n);
return 0;
}
/*
run:
1 2 3
8 9 4
7 6 5
*/