4. The following code attempts to set matrix zeroes in place but has a bug. What is the bug?
int[,] matrix = {
{1, 0, 3},
{4, 5, 6},
{7, 8, 9}
};
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
bool firstRowZero = false;
bool firstColZero = false;
// Check first row
for (int j = 0; j < cols; j++) {
if (matrix[0, j] == 0) firstRowZero = true;
}
// Check first column
for (int i = 0; i < rows; i++) {
if (matrix[i, 0] == 0) firstColZero = true;
}
// Use first row and column as markers
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i, j] == 0) {
matrix[i, 0] = 0;
matrix[0, j] = 0;
}
}
}
// Set zeroes based on markers
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i, 0] == 0 || matrix[0, j] == 0) {
matrix[i, j] = 0;
}
}
}
// Set first row zero if needed
if (firstRowZero) {
for (int j = 0; j < cols; j++) matrix[0, j] = 0;
}
// Set first column zero if needed
if (firstColZero) {
for (int i = 0; i < rows; i++) matrix[i, 0] = 0;
}