Zero out rows and columns

Zero out the corresponding rows and columns of a 2D matrix if any element is zero
/*
 * ZeroRowsAndColumns.cpp
 *
 *  Created on: Apr 13, 2012
 *      Author: Kiran Hegde
 */

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

/**
 * If any element of the matrix is zero, then make the entire row and column
 * zero too
 */
void zeroOutRowsAndColumsOfMatrix(int m, int n, int ** &matrix) {
    /*If any row or column needs to be zeroed out, the value will be
    initialized to true */
    bool *row = new bool[m];
    bool *column = new bool[n];
    //initialize row and column arrays to false
    for (int i = 0; i < m; i++)
        row[i] = false;
    for (int j = 0; j < n; j++)
        column[j] = false;
    //set the row and column array to true if a zero is found in that row, column
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (matrix[i][j] == 0) {
                row[i] = true;
                column[j] = true;
            }
        }
    }
    /*if any row or column was true, all elements of the matrix for that
      row or column is set to zero */
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (row[i] || column[j]) {
                matrix[i][j] = 0;
            }
        }
    }
    //release memory
    delete[] row;
    delete[] column;
}

void generateRandomMatrix(int m, int n, int ** &matrix) {
    //initialize a random seed
    srand(time(NULL));
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            matrix[i][j] = rand() % 9 + 1; //generate a random number from 1 to 9
        }
    }
    //introduce a couple of zeros
    int count = 0;
    while (count < 2) {
        int rowIndex = rand() % m; //random index between 0 and m - 1
        int colIndex = rand() % n; //random index between 0 and n - 1
        matrix[rowIndex][colIndex] = 0;
        count++;
    }
}

void printMatrix(int m, int n, int ** &matrix) {
    cout << "Matrix: " << endl;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}

/**
 * Test the code
 */
int main() {
    const int width = 10;
    const int height = 10;
    //allocate space for 2D array
    int **matrix = new int* [width];
    for (int i=0; i<width; i++) {
        matrix[i] = new int[height];
    }

    generateRandomMatrix(width, height, matrix);
    printMatrix(width, height, matrix);
    zeroOutRowsAndColumsOfMatrix(width, height, matrix);
    printMatrix(width, height, matrix);

    //delete 2D array
    for (int i=0; i<width; i++)
        delete [] matrix[i];
    delete [] matrix;
}
Comments