# 把矩阵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

At first glance, this problem seems easy: just iterate through the matrix and every time we see a 0, set that row and column to 0     There’s one problem with that solution though: we will “recognize” those 0s later on in our iteration and then set their row and column to zero  Pretty soon, our entire matrix is 0s!
One way around this is to keep a second matrix which flags the 0 locations   We would then do a second pass through the matrix to set the zeros   This would take O(MN) space.Do we really need O(MN) space?     No   Since we’re going to set the entire row and column to zero, do we really need to track which cell in a row is zero?  No   We only need to know that row 2, for example, has a zero.
The code below implement this algorithm    We keep track in two  arrays all the rows with zeros and all the columns with zeros  We then make a second pass of the matrix and set a cell to zero if its row or column is zero

void setZeros(int matrix[][],int m,int n)
{
int *row=(int *)malloc(m*sizeof(int));
int *column=(int *)malloc(n*sizeof(int));
int i,j;

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if (matrix[i][j]==0)
{
row[i]=1;
column[j]=1;
}
printf("%d ",matrix[i][j]);
}
printf("\n");
}

for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
if(row[i]==1||column[j]==1)
matrix[i][j]=0;
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}


• 本文已收录于以下专栏：

## Cracking coding interview(1.7) 设置某个位置为零的矩阵对应行列均为0

1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is s...

## n*n矩阵行列转换

• 2012-02-15 15:05
• 840B
• 下载

## 用STM32驱动的4*4行列矩阵键盘

• 2011-08-05 16:06
• 357KB
• 下载

## 矩阵键盘行列扫描

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)