把矩阵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");
}
}


面试题91：清除矩阵0所在行列

2016-06-02 09:55:04

将矩阵中0元素所对应的行列都清零

2015-08-17 15:57:45

将矩阵中值为0的元素所在的行和列设置为0， in-place O(1)space O（mn) time

2015-04-09 20:05:48

【Java】若MxN矩阵中某个元素为0， 则将其所在的行与列清零

2015-07-07 21:56:48

每天一道LeetCode-----给定一个矩阵，如果某个元素是0，就将所在行所在列上所有元素否置0

2017-12-01 15:11:29

将数组中0元素所在的行和列都置为0

2016-10-24 00:16:06

经典算法面试题目-置矩阵行列元素为0（1.7）

2016-07-31 23:15:14

给定一个m×n矩阵，如果一个元素为0，则将其整行和列的值设置为0.

2017-10-24 09:51:42

程序员面试金典1.7：若M*N矩阵中某个元素为0，则将其所在的行与列清零

2015-08-29 14:25:31

程序员面试金典： 9.1数组与字符串 7若M*N矩阵中某个元素为0，则将其所在行与列清零

2016-12-20 16:31:34