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;
            }
        }
    }
};
相关推荐
思考的笛卡尔1 小时前
密码学基础:RSA与AES算法的实现与对比
网络·算法·密码学
格林威7 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特9 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土10 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.10 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!10 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大10 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
智驱力人工智能11 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
学学学无无止境11 小时前
组合两个表-力扣
leetcode
程序员爱钓鱼11 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go