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

来源:互联网 发布:python获取request参数 编辑:程序博客网 时间:2024/06/18 16:31

题目

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

输出结果:

1 0
原创粉丝点击