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

举报
谙忆 发表于 2021/05/27 18:08:56 2021/05/27
1.7k+ 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. 写一个函数处理一个MxN的矩阵,如果矩阵中某个元素为0,那么把它所在的行和列都置为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.

写一个函数处理一个MxN的矩阵,如果矩阵中某个元素为0,那么把它所在的行和列都置为0.

解答

简单题。遍历一次矩阵,当遇到元素等于0时,记录下这个元素对应的行和列。
可以开一个行数组row和列数组col,当元素a[i][j]等于0时, 就把row[i]和col[j]置为1。
第二次遍历矩阵时,当某个元素对应的行row[i] 或列col[j]被设置为1,说明该元素在需要被置0的行或列上,因此将它(行/列)置0。

代码如下:

#include <iostream>
#include <cstring>
using namespace std;

void zero(int a[5][5], int m, int n){ bool row[m], col[n]; memset(row, 0, sizeof(row)); memset(col, 0, sizeof(col)); for(int i=0; i<m; ++i) for(int j=0; j<n; ++j) if(a[i][j] == 0){ row[i] = true; col[j] = true; } for(int i=0; i<m; ++i) for(int j=0; j<n; ++j) if(row[i] || col[j]) a[i][j] = 0;
}
int main()
{ int a[5][5] = { {1, 2, 3, 4,5}, {5, 6, 0, 7,8}, {9, 0, 1, 1,2}, {3, 4, 1, 1,9}, {4, 3, 0, 6,9} }; for(int i=0; i<5; ++i){ for(int j=0; j<5; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; zero(a, 5, 5); for(int i=0; i<5; ++i){ for(int j=0; j<5; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; return 0;
}

  
 

输出结果:

文章来源: chenhx.blog.csdn.net,作者:谙忆,版权归原作者所有,如需转载,请联系作者。

原文链接:chenhx.blog.csdn.net/article/details/52076512

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。