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

写一个算法使得把一个M*N的矩阵中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");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值