careercup7

来源:互联网 发布:云主机 知乎 编辑:程序博客网 时间:2024/06/01 09:22

记录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 4using 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 columnsfor(int j=0; j<M; j++)if(mat[i][j] == 0){  x[i] = 1;  y[j] = 1;}for(int i = 0; i<N;i++) //changefor(int j=0; j<M; j++)if(x[i] == 1 || y[j] == 1)mat[i][j] = 0;//printfor(int i = 0; i<N;i++){for(int j=0; j<M; j++)cout<<mat[i][j]<<" ";cout<<endl;}}