Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active November 18, 2017 01:56
Show Gist options
  • Save dgodfrey206/02a61c5e84fd514eb9b18e69eae0446f to your computer and use it in GitHub Desktop.
Save dgodfrey206/02a61c5e84fd514eb9b18e69eae0446f to your computer and use it in GitHub Desktop.
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and columns are set to 0
#include<vector>
#include<iostream>
using namespace std;
#define N 5
#define M 5
void zeroOutMatrix(int mat[N][M]) {
bool rowVisited[N] = {};
bool columnVisited[M] = {};
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (!rowVisited[i] && !columnVisited[j] && mat[i][j] == 0) {
for (int k = 0; k < N; k++)
mat[k][j] = 0;
for (int k = 0; k < M; k++)
mat[i][k] = 0;
rowVisited[i] = columnVisited[j] = true;
}
}
}
}
int main(){
int mat[N][M] = {{1,1,1,1,0},
{1,1,1,1,1},
{1,1,1,1,1},
{1,1,1,1,1},
{0,1,1,1,1}};
zeroOutMatrix(mat);
for(int i=0;i<N;i++) {
for(int j=0;j<M;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment