This post contain sparse matrix representation in java using array. Before that you may want to learn about the sparse matrix, click the link below.
Java program for Sparse Matrix Representation using Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | public class SparseMatrix { public static void main(String[] args) { // sparse matrix of class 5x6 with 6 non-zero values int sparseMatrix[][] = { {0, 0, 3, 0, 0}, {0, 0, 4, 0, 8}, {0, 0, 0, 0, 0}, {6, 0, 6, 0, 0} }; // Looking for non-zero values in the sparse matrix int size = 0; for (int i = 0; i < 4; i++){ for (int j = 0; j < 5; j++){ if (sparseMatrix[i][j] != 0){ size++; } } } //result matrix int resultMat[][] = new int[3][size]; // new matrix int k = 0; for (int i = 0; i < 4; i++){ for (int j = 0; j < 5; j++){ if (sparseMatrix[i][j] != 0) { resultMat[0][k] = i; resultMat[1][k] = j; resultMat[2][k] = sparseMatrix[i][j]; k++; } } } for (int i = 0; i < 3; i++){ for (int j = 0; j < size; j++) { System.out.printf("%d ", resultMat[i][j]); } System.out.printf("\n"); } } } |
Output:
1 2 3 | 0 1 1 3 3 2 2 4 0 2 3 4 8 6 6 |