CareerCup-1.7
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;
#define M 3
#define N 5
void setZero(int data[M][N])
{
bool row[M] = {0};
bool col[N] = {0};
for(int i=0; i<M; i++)
{
for(int j=0;j<N;j++)
{
if(data[i][j] == 0)
{
row[i] = 1;
col[j] = 1;
}
}
}
for(int i=0; i<M; i++)
if(row[i])
for(int j=0; j<N; j++)
data[i][j] = 0;
for(int j=0; j<N; j++)
if(col[j])
for(int i=0; i<M; i++)
data[i][j] = 0;
}
void print(int data[M][N])
{
cout<<"Print:"<<endl;
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
cout<<data[i][j]<<"\t";
cout<<endl;
}
cout<<"End"<<endl;
}
int main()
{
int data[M][N];
int count = 0;
for(int i=0; i<M; i++)
for(int j=0; j<N; j++)
data[i][j] = ++count;
data[0][0] = 0;
data[2][3] = 0;
data[2][4] = 0;
print(data);
setZero(data);
print(data);
system("pause");
};
#include <iostream>
using namespace std;
#define M 3
#define N 5
void setZero(int data[M][N])
{
bool row[M] = {0};
bool col[N] = {0};
for(int i=0; i<M; i++)
{
for(int j=0;j<N;j++)
{
if(data[i][j] == 0)
{
row[i] = 1;
col[j] = 1;
}
}
}
for(int i=0; i<M; i++)
if(row[i])
for(int j=0; j<N; j++)
data[i][j] = 0;
for(int j=0; j<N; j++)
if(col[j])
for(int i=0; i<M; i++)
data[i][j] = 0;
}
void print(int data[M][N])
{
cout<<"Print:"<<endl;
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
cout<<data[i][j]<<"\t";
cout<<endl;
}
cout<<"End"<<endl;
}
int main()
{
int data[M][N];
int count = 0;
for(int i=0; i<M; i++)
for(int j=0; j<N; j++)
data[i][j] = ++count;
data[0][0] = 0;
data[2][3] = 0;
data[2][4] = 0;
print(data);
setZero(data);
print(data);
system("pause");
};