把矩阵0元所在行列设置为0

翻译 2012年07月14日 21:02:19

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


相关文章推荐

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...

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

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

matlab中如何从一个矩阵的行列中找出 0 元素的个数 或者位置 并作为判断条件

问题描述:  2维数组A[2,100],要求根据A(1,:)中的非零元素的索引值来对数组做相应的处理!  在网上可以查阅到 find()函数的各种用法,也可以查询到 isnan()函数的用法,但是没有...

poj 3735 矩阵行列变换

这题是矩阵运算的经典题目。     可以将peanut初始化为{{0},{0},{0},{1}},然后对peanut矩阵进行变换(行变换,可以对单位矩阵操作,然后放在左边乘以peanut。列变换则放...

n*n矩阵行列转换

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

数据结构示例之矩阵行列和相等

以下为展示行列和相等的矩阵示例: 1.用c语言实现的版本 #include #include void main() { int a[16][16],i,j,n,k; printf("Ple...

矩阵键盘行列扫描

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)