Compressing 2-D Grids with Sparse Matrices

int rows = 11;
int cols = 11;
int[][] grid = new int[rows][cols];
grid[1][2] = 1;
grid[2][3] = 2;

// display the original grid
for (int[] row : grid) {
    for (int v : row) System.out.print(v + " ");
    System.out.println();
}

// count non-zero entries
int nonZero = 0;
for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        if (grid[i][j] != 0) nonZero++;

// build the compact representation
int[][] sparse = new int[nonZero + 1][3];
sparse[0][0] = rows;
sparse[0][1] = cols;
sparse[0][2] = nonZero;

int idx = 1;
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (grid[i][j] != 0) {
            sparse[idx][0] = i;
            sparse[idx][1] = j;
            sparse[idx][2] = grid[i][j];
            idx++;
        }
    }
}

// print the compressed form
for (int[] r : sparse)
    System.out.println(r[0] + "\t" + r[1] + "\t" + r[2]);

The first row of the sparse structure stores the original matrix’s diemnsions and the count of non-default values. Eacch subsequent row conatins the coordinates and value of one non-zero element, yielding:

11	11	2
1	2	1
2	3	2

Tags: sparse-matrix compression java algorithm

Posted on Thu, 20 Aug 2026 16:28:38 +0000 by ONiX