记录0位置,最后一次清零。否则前面清0后面无法正确判断是否是原有的0.
/*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>
#define N 4
#define M 4
using namespace std;
int main(){
int mat[N][N] = {{1,2,3,4},{5,6,0,8},{9,10,11,12},{13,0,15,16}};
int x[N]={0};
int y[M] = {0};
for(int i = 0; i<N;i++) //keep track of 0 rows and columns
for(int j=0; j<M; j++)
if(mat[i][j] == 0){
x[i] = 1;
y[j] = 1;
}
for(int i = 0; i<N;i++) //change
for(int j=0; j<M; j++)
if(x[i] == 1 || y[j] == 1)
mat[i][j] = 0;
//print
for(int i = 0; i<N;i++){
for(int j=0; j<M; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}