博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
把矩阵0元所在行列设置为0
阅读量:5960 次
发布时间:2019-06-19

本文共 1256 字,大约阅读时间需要 4 分钟。

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

转载于:https://www.cnblogs.com/JWMNEU/archive/2012/07/14/3069584.html

你可能感兴趣的文章
2015年末必备前端工具集
查看>>
【Solidity】8. 杂项 - 深入理解Solidity
查看>>
关于在VS2005中编写DLL遇到 C4251 警告的解决办法
查看>>
FT Partners CEO:Fintech游戏才刚刚开始,未来真正的关注点在这里
查看>>
Go语言大神亲述:历七劫方可成为程序员!
查看>>
【盘点】2017杭州云栖大会迁云实战Workshop
查看>>
Visual Studio 2008提高工作效率的小技巧
查看>>
深入研究Clang(七) Clang Lexer代码阅读笔记之Lexer
查看>>
对话依图医疗总裁倪浩:AI 产品只是第一步,未来要和医院制定中国儿童骨龄新标准...
查看>>
mysql并行复制
查看>>
Duilib学习笔记《06》— 窗体基类WindowImpBase
查看>>
共筑开放AI生态:ONNX标准得到华为、英特尔等更多厂商支持
查看>>
辅助企业IT进化的路上 数人云的不变与多变
查看>>
释放大数据生产力 Kyligence发布最新版旗舰产品KAP2.4
查看>>
惠普:应把大数据科学家作为一种共享资源
查看>>
中国人工智能学会通讯——自然语言处理中的技术评测
查看>>
开启openssl
查看>>
你必须关注超融合基础设施的理由
查看>>
善用佳软站长:畅谈大数据时代的知识管理
查看>>
AT&T:BYOD在2015年达“拐点”
查看>>