Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › MATRIX BASICS
A matrix is sparse when most of its entries are zero. "Most" means strictly more than half, so you compare the total number of zero entries with the total number of nonzero entries. A row having a zero does not decide anything by itself.
0 0 3 0
0 5 0 0
7 0 0 2The matrix has 12 entries. The zero entries are the two zeros and the last zero in the first row, the three zeros in the second row, and the two zeros in the third row, for 8 zeros altogether. The values 3, 5, 7, and 2 are the 4 nonzero entries. Since 8 is greater than 4, the whole matrix is sparse.
Why is the running matrix sparse?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
To count zeros, inspect every entry with the nested loops you already use for a matrix. Start zeroCount at 0, test each value against 0, and increase the counter only when the test succeeds. For the running matrix, the first row has three zero entries, so the counter becomes 3. The second row adds three more and reaches 6. The third row adds two and finishes at 8.
int zeroCount = 0;
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 4; column++) {
if (matrix[row][column] == 0) {
zeroCount++;
}
}
}After row 0: 3 zeros
After row 1: 6 zeros
After row 2: 8 zerosThe dimensions give the total number of entries without another counter: 3 rows multiplied by 4 columns equals 12. Once zeroCount is 8, the nonzero count is totalEntries - zeroCount, which is 12 - 8 = 4. The sparse test can therefore compare the zero count directly with that derived nonzero count.
int totalEntries = 3 * 4;
if (zeroCount > totalEntries - zeroCount) {
cout << "The matrix is sparse";
}The condition is zeroCount > totalEntries - zeroCount. Do not replace > with >=. If the two counts are equal, half the entries are zero and half are nonzero. That is not mostly zero, so an equal split is not sparse.
Replace the incorrect comparison with the strict condition that decides whether the running matrix is sparse.
if (zeroCount >= totalEntries - zeroCount) {
cout << "The matrix is sparse";
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The count follows the exact traversal: all 12 entries are inspected once, and each entry contributes at most one increase to zeroCount. The implementation needs the matrix, its dimensions, and a counter, but it does not create another matrix or change any entry. For a matrix with rows rows and columns columns, the time complexity is O(rows * columns), because every cell is checked, and the extra space is O(1), because only a fixed number of counters and dimension values are stored.