Skip to lesson

Matrix traversal

In Java, a 2D matrix int[][] grid is an array of row arrays, where grid.length is the number of rows (R) and grid[0].length is the number of columns (C). Mastering index coordinates (r, c) unlocks image processing, board games, and grid interviews.

Row loops, column loops, and diagonals

A matrix is a two-dimensional array of rows and columns; matrix[r][c] is the value in row r and column c.

A matrix is an array of rows, so cell (r, c) sits at grid[r][c]. You can visit it row by row, column by column, or along its two diagonals. The code below does all three.

Example 1 · Row-major, column-major, and diagonal sums on a 3x3 matrix

MatrixOrdersDemo.javaJava
public class MatrixOrdersDemo {    public static void main(String[] args) {        int[][] grid = {            {1, 2, 3},            {4, 5, 6},            {7, 8, 9}        };        int n = grid.length;
        StringBuilder rowMajor = new StringBuilder();        for (int r = 0; r < n; r++) {            for (int c = 0; c < n; c++) {                rowMajor.append(grid[r][c]).append(" ");            }        }
        StringBuilder colMajor = new StringBuilder();        for (int c = 0; c < n; c++) {            for (int r = 0; r < n; r++) {                colMajor.append(grid[r][c]).append(" ");            }        }
        int mainDiagSum = 0;        int antiDiagSum = 0;        for (int i = 0; i < n; i++) {            mainDiagSum += grid[i][i];            antiDiagSum += grid[i][n - 1 - i];        }
        System.out.println("Row-major     : " + rowMajor.toString().trim());        System.out.println("Column-major  : " + colMajor.toString().trim());        System.out.println("Main diag sum : " + mainDiagSum + " (1 + 5 + 9)");        System.out.println("Anti diag sum : " + antiDiagSum + " (3 + 5 + 7)");    }}
Output
Row-major     : 1 2 3 4 5 6 7 8 9
Column-major  : 1 4 7 2 5 8 3 6 9
Main diag sum : 15 (1 + 5 + 9)
Anti diag sum : 15 (3 + 5 + 7)

What this code does

  • Swapping the outer and inner loops switches between row-by-row (1 2 3 4 5 6 7 8 9) and column-by-column (1 4 7 2 5 8 3 6 9).
  • A single loop i = 0 .. n - 1 visits both the main diagonal grid[i][i] and the anti-diagonal grid[i][n - 1 - i] in O(n) time.

For a rectangular matrix grid with R = grid.length rows and C = grid[0].length columns, cell (r, c) sits at row r (0 <= r < R) and column c (0 <= c < C):

  • Row-major order (row by row, left to right): outer loop for (int r = 0; r < R; r++), inner loop for (int c = 0; c < C; c++). Because Java stores each row grid[r] as a contiguous int[] in memory, row-major order is also the most cache-friendly order.
  • Column-major order (column by column, top to bottom): outer loop for (int c = 0; c < C; c++), inner loop for (int r = 0; r < R; r++).
  • Diagonals of an n × n square matrix:
  • Main (primary) diagonal (top-left to bottom-right): cells where r == c, visited in one loop for (int i = 0; i < n; i++) at grid[i][i].
  • Anti-diagonal (secondary diagonal) (top-right to bottom-left): cells where r + c == n - 1, visited in one loop at grid[i][n - 1 - i].
  • Dimensions: int rows = grid.length; int cols = grid[0].length;.
  • Main diagonal: grid[i][i] for 0 <= i < n.
  • Anti-diagonal: grid[i][n - 1 - i] for 0 <= i < n.
  • Center overlap: when n is odd, grid[n / 2][n / 2] sits on both diagonals!

Transpose and rotate by 90 degrees in place (and real-world pixel grids)

In the real world, a digital photo or screen buffer is a 2D matrix of pixels pixels[r][c]. Flipping a photo horizontally reverses each row; rotating a photo 90 degrees clockwise rearranges rows into columns.

Example 2 · Brute force: copy into a new matrix (O(n²) time, O(n²) space)

RotateMatrixCopyDemo.javaJava
import java.util.Arrays;
public class RotateMatrixCopyDemo {    static int[][] rotate90Clockwise(int[][] matrix) {        int n = matrix.length;        int[][] rotated = new int[n][n];        for (int r = 0; r < n; r++) {            for (int c = 0; c < n; c++) {                rotated[c][n - 1 - r] = matrix[r][c]; // cell (r, c) moves to (c, n - 1 - r)            }        }        return rotated;    }
    public static void main(String[] args) {        int[][] pixels = {            {1, 2, 3},            {4, 5, 6},            {7, 8, 9}        };        for (int[] row : rotate90Clockwise(pixels)) {            System.out.println(Arrays.toString(row));        }    }}
Output
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]

What this code does

  • Every cell (r, c) is copied to its new position (c, n - 1 - r) in a second matrix.
  • This is simple and takes O(n²) time, but the second matrix doubles the memory to O(n²).

Example 3 · Optimal: transpose, then reverse each row (O(n²) time, O(1) space)

RotateMatrix90Demo.javaJava
import java.util.Arrays;
public class RotateMatrix90Demo {    static void rotate90Clockwise(int[][] matrix) {        int n = matrix.length;        // Step 1: Transpose upper triangle (c = r + 1 .. n - 1)        for (int r = 0; r < n; r++) {            for (int c = r + 1; c < n; c++) {                int tmp = matrix[r][c];                matrix[r][c] = matrix[c][r];                matrix[c][r] = tmp;            }        }        // Step 2: Reverse each row left-to-right        for (int r = 0; r < n; r++) {            int left = 0, right = n - 1;            while (left < right) {                int tmp = matrix[r][left];                matrix[r][left++] = matrix[r][right];                matrix[r][right--] = tmp;            }        }    }
    public static void main(String[] args) {        int[][] pixels = {            {1, 2, 3},            {4, 5, 6},            {7, 8, 9}        };        rotate90Clockwise(pixels);        for (int[] row : pixels) {            System.out.println(Arrays.toString(row));        }    }}
Output
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]

What this code does

  • After Step 1 (transpose), the rows are [1, 4, 7], [2, 5, 8], and [3, 6, 9].
  • After Step 2 (reverse each row), the rows become [7, 4, 1], [8, 5, 2], and [9, 6, 3] — a 90-degree clockwise rotation in O(1) extra space.
  • It is better than copying because both steps only swap cells inside the same matrix, so no second matrix is needed.
  1. Step 1 (Transpose): For r = 0 .. n - 1 and c = r + 1 .. n - 1, swap grid[r][c] with grid[c][r].
  2. Step 2 (Reverse rows): For each row r = 0 .. n - 1, reverse grid[r] in place.
  3. (For 90 degrees counter-clockwise: transpose first, then reverse each column* top-to-bottom.)*

The transpose of a matrix flips it across its main diagonal so row r, column c swaps with row c, column r (grid[r][c] <-> grid[c][r]). For an n × n square matrix, we transpose in place by looping r from 0 to n - 1 and c from r + 1 to n - 1 (the upper triangle only!). If you looped c from 0 to n - 1, every off-diagonal pair would swap twice and undo itself! Once you can transpose and reverse a row, rotating an n × n matrix 90 degrees clockwise in place (O(n²) time, O(1) space) is a 2-step recipe:

  1. Transpose the matrix across the main diagonal (swap(grid[r][c], grid[c][r]) for c > r).
  2. Reverse each row left-to-right (swap(grid[r][left], grid[r][right])).

Spiral order traversal with four shrinking boundaries

A spiral traversal visits cells clockwise, one layer at a time, using four shrinking boundaries: top, bottom, left and right. The code below walks a matrix this way.

In a while (top <= bottom && left <= right) loop:

  1. Walk c from left to right along grid[top][c], then increment top++ (the top row is finished).
  2. Walk r from top to bottom along grid[r][right], then decrement right-- (the right column is finished).
  3. If top <= bottom, walk c from right down to left along grid[bottom][c], then decrement bottom--.
  4. If left <= right, walk r from bottom down to top along grid[r][left], then increment left++.

Clockwise Spiral Traversal on a 3 × 4 Matrix

Step 1 of 5

Rowc0c1c2c3
r01234
r15678
r29101112
top
0
bottom
2
left
0
right
3
1. Top row (left -> right): visit row top = 0 across c = 0..3 (1, 2, 3, 4), then increment top++ to 1.

Example 4 · Spiral order traversal on both rectangular and single-row matrices

SpiralOrderDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class SpiralOrderDemo {    static List<Integer> spiralOrder(int[][] matrix) {        List<Integer> out = new ArrayList<>();        int top = 0, bottom = matrix.length - 1;        int left = 0, right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {            for (int c = left; c <= right; c++) out.add(matrix[top][c]);            top++;
            for (int r = top; r <= bottom; r++) out.add(matrix[r][right]);            right--;
            if (top <= bottom) {                for (int c = right; c >= left; c--) out.add(matrix[bottom][c]);                bottom--;            }            if (left <= right) {                for (int r = bottom; r >= top; r--) out.add(matrix[r][left]);                left++;            }        }        return out;    }
    public static void main(String[] args) {        int[][] rect = {            {1,  2,  3,  4},            {5,  6,  7,  8},            {9, 10, 11, 12}        };        System.out.println("3x4 spiral : " + spiralOrder(rect));
        int[][] singleRow = {{10, 20, 30}};        System.out.println("1x3 spiral : " + spiralOrder(singleRow));    }}
Output
3x4 spiral : [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
1x3 spiral : [10, 20, 30]

What this code does

  • On the 3 × 4 matrix, the outer ring [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] is collected first, shrinking the box to top=1, bottom=1, left=1, right=2 ([6, 7]).
  • On the 1 × 3 matrix, after the top pass increments top from 0 to 1, top <= bottom (1 <= 0) is false, so the bottom pass does not re-read [20, 10].

To visit all R × C cells in clockwise spiral order (top row left-to-right, right column top-to-bottom, bottom row right-to-left, left column bottom-to-top, then repeat one layer inward), maintain four boundary indices:

  • top = 0, bottom = R - 1, left = 0, right = C - 1.

The two inner if guards in steps 3 and 4 prevent double-reading a single remaining row (like a 1 × 4 matrix) or a single remaining column (like a 4 × 1 matrix).

Never skip the if (top <= bottom) check before the bottom-row pass or if (left <= right) before the left-column pass — non-square matrices like 1 x 3 will duplicate elements without them!

Next step

Check your understanding

10 quick questions