Print Spiral Number Pattern in Java
Problem
A spiral number pattern fills a square grid one ring at a time, laying numbers down the top row, then the right column, then the bottom row, then the left column, before spiraling inward and repeating for the next ring in.
Given a size n, fill an n x n grid with the numbers 1 through n squared in clockwise spiral order, and print it.
Java Program
public class SpiralNumberPattern {
public static void main(String[] args) {
int n = 4;
int[][] grid = new int[n][n];
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) grid[top][j] = num++;
top++;
for (int i = top; i <= bottom; i++) grid[i][right] = num++;
right--;
if (top <= bottom) { // a bottom row still remains below the last-filled top row
for (int j = right; j >= left; j--) grid[bottom][j] = num++;
bottom--;
}
if (left <= right) { // a left column still remains inside the last-filled right column
for (int i = bottom; i >= top; i--) grid[i][left] = num++;
left++;
}
}
for (int[] row : grid) {
StringBuilder line = new StringBuilder();
for (int v : row) {
if (line.length() > 0) line.append(" ");
line.append(v);
}
System.out.println(line);
}
}
}Output
Core Logic
Tracking four shrinking boundaries — top, bottom, left, right — and walking each one in turn (right along the top, down the right side, left along the bottom, up the left side) lays down one full ring before moving one step inward for the next.
- 1
top,bottom,left, andrightstart at the grid's outer edges, andnumstarts at1. - 2Each lap fills the current top row left-to-right, then the current right column top-to-bottom, then advances
topdown andrightleft by one. - 3If any rows remain, it fills the current bottom row right-to-left, then the current left column bottom-to-top, advancing
bottomup andleftright by one. - 4The
while (top <= bottom && left <= right)loop keeps spiraling inward, one ring per lap, until the boundaries cross and every cell has been assigned.
n = 4, the first lap fills the outer ring — 1 through 4 across the top, 5 and 6 down the right, 7 through 9 across the bottom, 10 through 12 up the left — before the second lap fills the inner 2x2 ring with 13 through 16.Key Point: The two guard checks — if (top <= bottom) before the bottom row and if (left <= right) before the left column — matter for odd-sized grids and the very last ring, where a row or column can otherwise get filled twice.
Why: Every cell of the n x n grid is visited exactly once to assign it a number, and the filled grid itself is stored in memory before being printed.