leetcode矩阵置零

题目:

. - 力扣(LeetCode)

代码:

cpp 复制代码
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        bool row1 = false;
        bool column1 = false;
        int m = matrix.size();
        int n = matrix[0].size();
        //记录第一行有没有0
        for(int i = 0;i < n;i++){
            if(matrix[0][i] == 0){
                row1 = true;
                break;
            }
        }
        //记录第一列有没有0
        for(int i = 0;i < m;i++){
            if(matrix[i][0] == 0){
                column1 = true;
                break;
            }
        }
        //借用第一行第一列标记0
        for(int i = 1;i < m;i++){
            for(int j = 1;j < n;j++){
                if(matrix[i][j] == 0){
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        //正式操作
        for(int i = 1;i < m;i++){
            for(int j = 1;j < n;j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                    matrix[i][j] = 0;
                }
            }
        }
        //把第一行具体操作
        if(row1){
            for(int i = 0;i < n;i++){
                matrix[0][i] = 0;
            }
        }
        //把第一列具体操作
        if(column1){
            for(int i = 0;i < m;i++){
                matrix[i][0] = 0;
            }
        }
    }
};
相关推荐
汉克老师3 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh4 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
c++bug5 小时前
六级第一关——下楼梯
算法
Morri35 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛5 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
AndrewHZ5 小时前
【3D算法技术】blender中,在曲面上如何进行贴图?
算法·3d·blender·贴图·三维建模·三维重建·pcg
Jared_devin6 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯
AI 嗯啦7 小时前
数据结构深度解析:二叉树的基本原理
数据结构·算法
和光同尘@8 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_028 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode