C++ Online Compiler
Example: SetMatrixZerosInPlace in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// SetMatrixZerosInPlace #include <iostream> #include <vector> void printMatrix(const std::vector<std::vector<int>>& matrix) { for (const auto& row : matrix) { for (int val : row) { std::cout << val << " "; } std::cout << std::endl; } } int main() { // Step 1: Define the input matrix std::vector<std::vector<int>> matrix = { {1, 1, 1}, {1, 0, 1}, {1, 1, 1} }; int R = matrix.size(); int C = matrix[0].size(); bool firstRowHasZero = false; bool firstColHasZero = false; // Step 2: Check if the first row has any zeros for (int j = 0; j < C; ++j) { if (matrix[0][j] == 0) { firstRowHasZero = true; break; } } // Step 3: Check if the first column has any zeros for (int i = 0; i < R; ++i) { if (matrix[i][0] == 0) { firstColHasZero = true; break; } } // Step 4: Use first row and column as markers for the rest of the matrix // (excluding the first row and column themselves) for (int i = 1; i < R; ++i) { for (int j = 1; j < C; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; // Mark corresponding first column element matrix[0][j] = 0; // Mark corresponding first row element } } } // Step 5: Set elements to zero based on markers in the first row/column // (excluding the first row and column themselves) for (int i = 1; i < R; ++i) { for (int j = 1; j < C; ++j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } // Step 6: Apply zeros to the first row if it originally had a zero if (firstRowHasZero) { for (int j = 0; j < C; ++j) { matrix[0][j] = 0; } } // Step 7: Apply zeros to the first column if it originally had a zero if (firstColHasZero) { for (int i = 0; i < R; ++i) { matrix[i][0] = 0; } } // Step 8: Print the modified matrix std::cout << "Original Matrix:" << std::endl; std::vector<std::vector<int>> original_matrix = { {1, 1, 1}, {1, 0, 1}, {1, 1, 1} }; printMatrix(original_matrix); std::cout << "\nMatrix after setting zeros (In-Place):" << std::endl; printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS