Spiral Number Pattern
C
Medium
6 views
Problem Description
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Fill the numbers in the matrix in spiral order. Change direction at the boundaries.
Official Solution
#include <stdio.h>
int main() {
int n = 4; // Size of the matrix
int mat[n][n];
int num = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (num <= n * n) {
// Top row (left to right)
for (int i = left; i <= right && num <= n*n; i++)
mat[top][i] = num++;
top++;
// Right column (top to bottom)
for (int i = top; i <= bottom && num <= n*n; i++)
mat[i][right] = num++;
right--;
// Bottom row (right to left)
for (int i = right; i >= left && num <= n*n; i--)
mat[bottom][i] = num++;
bottom--;
// Left column (bottom to top)
for (int i = bottom; i >= top && num <= n*n; i--)
mat[i][left] = num++;
left++;
}
// Print the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d ", mat[i][j]); // %3d for alignment
printf("n");
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!