Skip to content

Instantly share code, notes, and snippets.

@KorbenC
Created December 18, 2013 18:52
Show Gist options
  • Save KorbenC/8027701 to your computer and use it in GitHub Desktop.
Save KorbenC/8027701 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 column is set to 0.
#include<iostream>
using namespace std;
int main()
{
int m = 3;
int n = 3;
int array[3][3] = {{1,2,3},{4,5,6}, {7,8,9}};
int row[3*3];
int column[3*3];
int count = 0;
for(int row=0; row < m; row++)
{
for(int col=0; col < n; col++)
{
cout << array[row][col];
}
cout << endl;
}
for(int i=0; i < m; i++)
{
for(int j=0; j < n; j++)
{
if(array[i][j] == 0)
{
row[count] = i;
column[count] = j;
count++;
}
}
}
cout << endl << endl;
for(int i=0; i < count; i++)
{
for(int j=0; j < n; j++)
{
if(row[i] + j < 3)
{
array[row[i] + j][column[i]] = 0;
}
if(row[i] - j >= 0)
{
array[row[i] - j][column[i]] = 0;
}
}
for(int j=0; j < n; j++)
{
if(column[i] + j < 3)
{
array[row[i]][column[i]+j] = 0;
}
if(row[i] - j >= 0)
{
array[row[i]][column[i]-j] = 0;
}
}
}
for(int row=0; row < m; row++)
{
for(int col=0; col < n; col++)
{
cout << array[row][col];
}
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment