Practice/expertSpiral Matrix Pattern
⏱ 00:00
Best: 0/100
Matrix Traversal & Boundary SimulationTarget Time: 25 mins

Spiral Matrix Pattern

Given an integer N, generate and print an N x N matrix filled clockwise with numbers 1 to N² in spiral order. Separate numbers on each row with a single space.

Input Format
A single integer N.
Output Format
Print N rows with N space-separated numbers.
Constraints:1 <= N <= 10
Concepts Required:
4-pointer boundary traversal (top, bottom, left, right)2D matrix indexingSimulation algorithms
Expected Pattern PreviewASCII Monospace
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7

Notice how character spacing and row counts scale systematically based on the input N.

Concrete Examples

Example 1
Input:
4
Output:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

Explanation: Fills 1 to 16 in a clockwise inward spiral.

Example 2
Input:
3
Output:
1 2 3
8 9 4
7 6 5

Explanation: Fills 1 to 9 in spiral order.

← Back to All Challenges