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.
写一个算法加入M*N矩阵中有一个元素为0,那么该元素对应的行和列的所有元素均设为0
分析:如果直接循环二维数组,当该数组元素为0时,把对应的行和列的元素均设为0.这样有可能会遇到这样一个问题,就是可能本来该行或该列的某个元素(假设为A)本来不为0的,但经过修改后为0,当遍历到该元素A时,因为该位置上为0,因此把该行该列元素均置为0造成错误。
可以设置一个flag数组。我下面设计的算法有点冗余。答案上是假设有元素A,A为0,则先把改行该列的所有元素的flag设为true,然后遍历完所有的元素。
再根据flag真假进行元素的更新。
#include<iostream> using namespace std; template<size_t rows,size_t cols> void setZero(int (&matrix)[rows][cols],bool (&flag)[rows][cols]) { //flag为true代表这个元素为0是修改之后的结果,而不是原始数据为0 for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ if(matrix[i][j]==0&&flag[i][j]==false){ for(int k=0;k<cols;k++){ if(matrix[i][k]!=0) flag[i][k]=true; matrix[i][k]=0; } for(int l=0;l<rows;l++){ if(matrix[l][j]!=0) flag[l][j]=true; matrix[l][j]=0; } } } } } int main(){ int A[][4]={3,0,5,1,4,2,3,1,1,3,2,5}; bool flag[3][4]={false}; setZero(A,flag); for(int i=0;i<3;i++){ for(int j=0;j<4;j++) cout<<A[i][j]<<" "; cout<<endl; } system("pause"); }