Command Palette

Search for a command to run...

Lesson 2.4 · Arrays

Matrices and 2D Arrays

Rows and columns, walking neighbours safely with direction arrays, and the boundary technique for spirals and layers.

12 min

Think of it like this

A matrix is a city map of square blocks. Every block has an address (row, column) and up to four neighbours: north, south, east and west. Walking off the edge of the map is the most common way to get lost.

1.Rows, columns and bounds

m.length is the number of rows, m[0].length the number of columns. Cell (r, c) is valid when 0 ≤ r < rows and 0 ≤ c < cols. Check bounds before every read of a neighbour.

2.Direction arrays

Instead of writing four nearly identical blocks for up, down, left and right, list the moves once in an array and loop over them. Add four diagonal pairs when you need eight directions.

Neighbours.java
public class Main {
    static final int[][] DIRS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};   // up, down, left, right

    public static void main(String[] args) {
        int[][] m = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int r = 0, c = 1, sum = 0;
        for (int[] d : DIRS) {
            int nr = r + d[0], nc = c + d[1];
            if (nr < 0 || nc < 0 || nr >= m.length || nc >= m[0].length) continue;
            sum += m[nr][nc];
        }
        System.out.println("neighbours of (0,1) sum to " + sum);   // 5 + 1 + 3
    }
}

Output

neighbours of (0,1) sum to 9

3.Boundaries for spirals and layers

For spiral order or rotating layer by layer, keep four boundaries: top, bottom, left, right. Walk one edge, then move that boundary inwards. Stop when the boundaries cross. You'll use this in the Spiral Matrix problem.

Remember

  • rows = m.length, cols = m[0].length.
  • Use a direction array and one bounds check for neighbours.
  • Shrink four boundaries to walk spirals and layers.

Common mistakes

  • Swapping rows and columns in bounds checks.
  • Reading m[0].length on an empty matrix.