Java Programs›Arrays›Print Matrix in Spiral Order

Print Matrix in Spiral Order in Java

intermediate·  Arrays  ·  Matrix

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.

Input
[[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Java Program

Java
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

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

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.

How It Works
  1. 1top and bottom start at the first and last row, left and right at the first and last column.
  2. 2Each round reads the top row left to right, then the right column top to bottom, shrinking top and right as it goes.
  3. 3The bottom row (right to left) and the left column (bottom to top) are read only if top <= bottom and left <= right still hold.
  4. 4The while loop stops once the boundaries cross, meaning every cell has been added to order.
The sample is built so its spiral reads 1 to 12: the outer ring gives 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.

Complexity
Time Complexity: O(r × c)Space Complexity: O(r × c)

Why: Every cell is added exactly once; the output list holds all r × c values, while the boundaries themselves need constant space.

Key Concepts

2D arrayboundary pointerswhile loopArrayList

Approach 2: Direction Vectors

Java
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

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

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.

How It Works
  1. 1dRow and dCol encode the four moves in clockwise order: right, down, left, up.
  2. 2A visited matrix records every cell already added to order.
  3. 3Before each move, the next cell is checked; if it's out of bounds or visited, dir = (dir + 1) % 4 turns clockwise.
  4. 4The loop runs exactly rows * cols times, once per cell.
After reading 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.

Complexity
Time Complexity: O(r × c)Space Complexity: O(r × c)

Why: Each cell is visited once, and the visited matrix adds another r × c of memory on top of the output list.

Key Concepts

direction arraysvisited matrixmodulo arithmetic

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.

Learn the Concept

Related Programs