Java Perfect Square Spiral Pattern

Intermediate
7 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A perfect square spiral fills an n × n grid with numbers 1..n² in a clockwise path — outer ring first, then the next ring inward.

Remember
Rule: for each layer [low..high]
  top → right → bottom → left
  then low++, high--

   1   2   3   4   5
  16  17  18  19   6
  15  24  25  20   7
  14  23  22  21   8
  13  12  11  10   9     ← n = 5

Finale of the Java number-pattern series — graduate from 1D loops (Program 61) to a full 2D spiral matrix.

How to Solve It

Allocate a 2D array, walk four edges per layer with shrinking low/high, then print with fixed width.

MethodIdeaBest for
Fixed nHard-coded 10×10 fill + printLabs and demos
Scanner inputSame fill; read n at runtimeInteractive practice
fillSpiral helperSeparate fill and print methodsCleaner structure

Pseudocode

Pseudocode
a = new int[n][n]
low = 0, high = n - 1, val = 1

for each layer while low <= high:
    for j = low to high:     a[low][j] = val++     // top
    for i = low+1 to high:   a[i][high] = val++    // right
    for j = high-1 down to low: a[high][j] = val++ // bottom
    for i = high-1 down to low+1: a[i][low] = val++ // left
    low++; high--

print each a[i][j] with width 4

Cheat sheet

GoalPattern
Allocateint[][] a = new int[n][n];
Boundsint low = 0, high = n - 1;
Layers(n + 1) / 2 rings
Avoid double cornersRight starts at low+1; left ends at low+1
Align columnsSystem.out.printf("%4d", a[i][j]);
End rowSystem.out.println();

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printf / printStays on the same lineEach cell in a row
System.out.printlnEnds the lineAfter each matrix row

Build the row with printf, then break once.

Live Preview

Change n and the perfect square spiral updates instantly.

Whole numbers from 3 to 8. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · cells = 25
   1   2   3   4   5
  16  17  18  19   6
  15  24  25  20   7
  14  23  22  21   8
  13  12  11  10   9

Worked Walkthrough — n = 3

Outer ring fills 1..8; the center cell is 9.

EdgePathValues
Top(0,0)→(0,2)1 2 3
Right(1,2)→(2,2)4 5
Bottom(2,1)→(2,0)6 7
Left(1,0)8
Center(1,1) next layer9
Final 3×3
   1   2   3
   8   9   4
   7   6   5

Right starts at low+1 so the top-right corner (3) is not overwritten.

Java Programs

Three complete programs: fixed 10×10, Scanner size, and a fillSpiral helper. Use View Output to reveal sample results.

Example 1 — Fixed n = 10

Hard-coded 10×10 — four edge loops per layer with low and high.

Java
public class PerfectSquareSpiral {
    public static void main(String[] args) {
        int n = 10;
        int[][] a = new int[n][n];
        int low = 0, high = n - 1, val = 1;

        for (int layer = 0; layer < (n + 1) / 2; layer++, low++, high--) {
            for (int j = low; j <= high; j++, val++) a[low][j] = val;
            for (int i = low + 1; i <= high; i++, val++) a[i][high] = val;
            for (int j = high - 1; j >= low; j--, val++) a[high][j] = val;
            for (int i = high - 1; i > low; i--, val++) a[i][low] = val;
        }

        System.out.println("Perfect Square Spiral");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.printf("%4d", a[i][j]);
            System.out.println();
        }
    }
}

How It Works

1. Allocate. int[n][n] holds every spiral value before printing.

2. Four edges. Each layer fills top → right → bottom → left, then shrinks with low++ / high--.

3. Print. printf("%4d", ...) keeps columns aligned for 1–100.

Example 2 — Scanner Input

Read n and fill an n × n spiral — same four-edge logic.

Java
import java.util.Scanner;

public class PerfectSquareSpiralInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter matrix size n: ");
        if (!sc.hasNextInt()) {
            System.out.println("Please enter a positive integer.");
            return;
        }
        int n = sc.nextInt();
        if (n <= 0) {
            System.out.println("Please enter a positive integer.");
            return;
        }

        int[][] a = new int[n][n];
        int low = 0, high = n - 1, val = 1;
        for (int layer = 0; layer < (n + 1) / 2; layer++, low++, high--) {
            for (int j = low; j <= high; j++, val++) a[low][j] = val;
            for (int i = low + 1; i <= high; i++, val++) a[i][high] = val;
            for (int j = high - 1; j >= low; j--, val++) a[high][j] = val;
            for (int i = high - 1; i > low; i--, val++) a[i][low] = val;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.printf("%4d", a[i][j]);
            System.out.println();
        }
        sc.close();
    }
}

How It Works

1. Validate. Require a positive integer before allocating the matrix.

2. Same fill. Only the source of n changes — layers and edges match Example 1.

3. Odd n. For n = 5, the center cell is 25 on the last (single-cell) layer.

Example 3 — fillSpiral Helper

Refactor layer logic into fillSpiral and print with printMatrix.

Java
public class SpiralMatrixHelper {
    static void fillSpiral(int[][] a, int n) {
        int low = 0, high = n - 1, val = 1;
        for (int layer = 0; layer < (n + 1) / 2; layer++, low++, high--) {
            for (int j = low; j <= high; j++, val++) a[low][j] = val;
            for (int i = low + 1; i <= high; i++, val++) a[i][high] = val;
            for (int j = high - 1; j >= low; j--, val++) a[high][j] = val;
            for (int i = high - 1; i > low; i--, val++) a[i][low] = val;
        }
    }

    static void printMatrix(int[][] a, int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.printf("%4d", a[i][j]);
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int n = 10;
        int[][] a = new int[n][n];
        fillSpiral(a, n);
        printMatrix(a, n);
    }
}

How It Works

1. Separate concerns. fillSpiral only writes values; printMatrix only formats them.

2. Same algorithm. Layer count and edge loops match Examples 1 and 2.

3. Reuse. Call fillSpiral from tests or other mains without duplicating the ring logic.

Edge Cases & Pitfalls

Check these before calling the solution done.

Double corner

Wrong bounds

Right must start at low+1; left must stop before low. Overlapping corners overwrite values.

Forget shrink

Infinite / stuck layer

Always low++ and high-- after the four edges, or the same ring repeats.

n = 1

Single cell

Output is just 1 — one layer, top loop only.

Odd n

Center cell

Innermost layer is one cell (e.g. 25 for n = 5). Loops still work.

No printf

Misaligned columns

Two- and three-digit numbers need fixed width (%4d) or the grid looks skewed.

n ≤ 0

Bad allocate

Reject non-positive sizes before new int[n][n].

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(n²) for the matrix

Every cell is written once → n² assignments. The 2D array itself uses O(n²) memory.

Key Takeaways

  • Rule: fill top → right → bottom → left, then shrink low/high.
  • Corners: skip already-written corners on right and left edges.
  • Layers: (n + 1) / 2 rings cover the whole square.
  • Complexity: O(n²) time and space for size n.

One line: walk each ring of the square clockwise, then move one layer inward.

Frequently Asked Questions

It fills an n×n (perfect square) grid with numbers 1..n² in a clockwise spiral, starting at the top-left and moving inward layer by layer.
They mark the current layer’s top/bottom row and left/right column. After filling four edges, increment low and decrement high to shrink the active rectangle.
The top row already wrote the top-right corner at (low, high). Starting at low + 1 avoids writing that cell twice.
Yes. Allocate int[n][n] and run (n + 1) / 2 layers. The same four edge loops work for any positive n — see Example 2.
O(n²) — every cell is assigned exactly once, so work grows with the number of cells.
Yes. Reorder the four edge fills and adjust loop bounds so corners are not duplicated.
The innermost layer is a single cell. The last loops still work; for n=5 the center is 25.
Call sc.hasNextInt() before sc.nextInt() and validate n > 0 so bad input does not throw InputMismatchException.

Did you know?

Fills an n×n matrix in spiral order using low/high boundaries — top, right, bottom, left edges per layer. O(n²) time and space.

Next: Java Star Pattern Programs

Continue with star patterns — the next series after number patterns.

Star patterns hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful