Print Matrix in Spiral Order in Java
Problem
A spiral traversal starts at the top-left corner and moves right, down, left and up around the outer edge of the matrix, then repeats on the next ring inward until every cell has been visited once.
Given a matrix of any shape, list its elements in clockwise spiral order.
Java Program
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{10, 11, 12, 5},
{9, 8, 7, 6}
};
List<Integer> order = new ArrayList<>();
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) order.add(matrix[top][j]); // across the top row
top++;
for (int i = top; i <= bottom; i++) order.add(matrix[i][right]); // down the right column
right--;
if (top <= bottom) { // a row is still left to walk back along
for (int j = right; j >= left; j--) order.add(matrix[bottom][j]);
bottom--;
}
if (left <= right) { // a column is still left to climb
for (int i = bottom; i >= top; i--) order.add(matrix[i][left]);
left++;
}
}
System.out.println(order);
}
}Output
Core Logic
Four boundaries — top, bottom, left and right — mark the ring still to be walked; after each side is read, its boundary moves one step inward.
- 1
topandbottomstart at the first and last row,leftandrightat the first and last column. - 2Each round reads the top row left to right, then the right column top to bottom, shrinking
topandrightas it goes. - 3The bottom row (right to left) and the left column (bottom to top) are read only if
top <= bottomandleft <= rightstill hold. - 4The
whileloop stops once the boundaries cross, meaning every cell has been added toorder.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and the inner ring is the single row 11, 12.Key Point: The two if checks prevent double-counting — when only one row or one column is left, walking back along it would add the same cells a second time.
Why: Every cell is added exactly once; the output list holds all r × c values, while the boundaries themselves need constant space.
Key Concepts
Approach 2: Direction Vectors
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrixDirections {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{10, 11, 12, 5},
{9, 8, 7, 6}
};
int rows = matrix.length, cols = matrix[0].length;
int[] dRow = {0, 1, 0, -1}; // right, down, left, up
int[] dCol = {1, 0, -1, 0};
boolean[][] visited = new boolean[rows][cols];
List<Integer> order = new ArrayList<>();
int r = 0, c = 0, dir = 0;
for (int step = 0; step < rows * cols; step++) {
order.add(matrix[r][c]);
visited[r][c] = true;
int nextR = r + dRow[dir], nextC = c + dCol[dir];
if (nextR < 0 || nextR >= rows || nextC < 0 || nextC >= cols || visited[nextR][nextC]) {
dir = (dir + 1) % 4; // blocked ahead, so turn clockwise
nextR = r + dRow[dir];
nextC = c + dCol[dir];
}
r = nextR;
c = nextC;
}
System.out.println(order);
}
}
Output
Core Logic
Instead of tracking four boundaries, simulate walking through the grid: keep moving in the current direction and turn clockwise whenever the next step would leave the matrix or hit a visited cell.
- 1
dRowanddColencode the four moves in clockwise order: right, down, left, up. - 2A
visitedmatrix records every cell already added toorder. - 3Before each move, the next cell is checked; if it's out of bounds or visited,
dir = (dir + 1) % 4turns clockwise. - 4The loop runs exactly
rows * colstimes, once per cell.
4 at the top-right corner, moving right would leave the grid, so the walker turns down and reads 5 next.Key Point: This version is easier to get right under interview pressure because there are no boundary edge cases to remember, at the cost of an extra boolean matrix.
Why: Each cell is visited once, and the visited matrix adds another r × c of memory on top of the output list.
Key Concepts
Interview Questions
Which edge cases break naive spiral code?
A single row, a single column, or a non-square matrix can make the loop walk back over cells already printed. The boundary checks before the bottom row and left column prevent that.
What's the time complexity of a spiral traversal?
O(rows × cols), since every cell is visited exactly once.