Matrices

Basic Algorithms
≈ 2 min read

Two-dimensional data as an array of rows

In algorithmic problems, a matrix can conveniently be represented as a two-dimensional array. The first index selects a row, and the second selects a column.

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};

int value = matrix[1][2]; // 6

For this matrix, matrix.length is the number of rows, while matrix[row].length is the number of elements in a particular row. This distinction matters: in Java, a two-dimensional array is technically an array of arrays, so row lengths may differ.

Traversing rows and columns

A full matrix traversal usually uses two nested loops: the outer loop selects a row, and the inner loop visits its elements.

int sum = 0;

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        sum += matrix[row][col];
    }
}

If a matrix has rows rows and cols columns, a full traversal of a rectangular matrix takes O(rows × cols) time because every cell is visited.

Neighboring cells and boundaries

Many problems require inspecting neighbors of the current cell: above, below, left, or right. Before accessing a neighbor, you must check that its coordinates remain inside the matrix.

int row = 1;
int col = 1;

if (row > 0) {
    int top = matrix[row - 1][col];
}

if (col + 1 < matrix[row].length) {
    int right = matrix[row][col + 1];
}

These checks may look minor, but correct coordinate handling becomes the foundation for more advanced algorithms on tables and grids.

Do not assume every row has the same length. If the problem does not guarantee a rectangular matrix, column boundaries must be checked with matrix[row].length for the current row.