C++ Online Compiler
Example: SetMatrixZerosAuxiliaryArrays in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// SetMatrixZerosAuxiliaryArrays #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(); // Number of rows int C = matrix[0].size(); // Number of columns // Step 2: Initialize auxiliary arrays to track zero rows and columns std::vector<bool> row_zeros(R, false); std::vector<bool> col_zeros(C, false); // Step 3: First pass - Identify rows and columns containing zeros for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { if (matrix[i][j] == 0) { row_zeros[i] = true; col_zeros[j] = true; } } } // Step 4: Second pass - Set elements to zero based on auxiliary arrays for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { if (row_zeros[i] || col_zeros[j]) { matrix[i][j] = 0; } } } // Step 5: 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 (Auxiliary Arrays):" << std::endl; printMatrix(matrix); return 0; }
Output
Clear
ADVERTISEMENTS