CC189 - 1.8

博客围绕矩阵元素处理算法展开,若 MxN 矩阵中某元素为 0,则将其所在行和列都置为 0。给出了两种解法,分别使用两个布尔数组和两个布尔变量,还提供了代码链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.

解法一:two bool arrays

void zero(vector<vector<int>> &matrix){
    int n = matrix.size();
    int m = matrix[0].size();
    bool row[n] = {};
    bool col[m] = {};
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(matrix[i][j]==0){
                row[i] = true;
                col[j] = true;
            }
        }
    }
    for(int i=0;i<n;i++){
        if(row[i]){
            for(int j=0;j<m;j++){
                matrix[i][j] = 0;
            }
        }
    }
    for(int j=0;j<m;j++){
        if(col[j]){
            for(int i=0;i<n;i++){
                matrix[i][j] = 0;
            }
        }
    }
}

解法二:two bool variables

void zero(vector<vector<int>> &matrix){
    bool row = false;
    bool col = false;
    int n = matrix.size();
    int m = matrix[0].size();
    for(int i=0;i<n;i++){
        if(matrix[i][0]==0){
            col = true;
            break;
        }
    }
    for(int j=0;j<m;j++){
        if(matrix[0][j]==0){
            row = true;
            break;
        }
    }
    for(int i=1;i<n;i++){
        for(int j=1;j<m;j++){
            if(matrix[i][j]==0){
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }
    }
    for(int i=0;i<n;i++){
        if(matrix[i][0]==0){
            for(int j=1;j<m;j++){
                matrix[i][j] = 0;
            }
        }
    }
    for(int j=0;j<m;j++){
        if(matrix[0][j]==0){
            for(int i=0;i<n;i++){
                matrix[i][j] = 0;
            }
        }
    }
    if(row){
        for(int j=0;j<m;j++){
            matrix[0][j] = 0;
        }
    }
    if(col){
        for(int i=0;i<n;i++){
            matrix[i][0] = 0;
        }
    }
}

https://onlinegdb.com/rkAKv2CjV

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值