Leetcode 73 矩阵置0

java 复制代码
class Solution {
    //1.用矩阵的第一行和第一列来标记该行或该列是否应该为0,但是这样的话忽视了第一行或第一列为0的情况
    //2.用标记row0和column0来标记第一行或第一列是否该为0
    public void setZeroes(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        boolean row0 = false;
        boolean column0 = false;
        for(int i = 0; i < n; i++){
            if(matrix[i][0] == 0){
                column0 = true;
            }

        }
        for(int j = 0; j < m; j++){
            if(matrix[0][j] == 0){
                row0 = true;

            }
        }
        for(int i = 1; i < n; i++){
            for(int j = 1; j < m; j++){
                if(matrix[i][j] == 0){
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        for(int i = 1; i < n; i++){
            for(int j = 1; j < m; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
            }
        }
        if(row0){
            for(int i = 0; i < m; i++) matrix[0][i] = 0;
        }
        if(column0){
            for(int i = 0; i < n; i++) matrix[i][0] = 0;
        }
    }
}
相关推荐
点云SLAM22 分钟前
图论中邻接矩阵和邻接表详解
算法·图论·slam·邻接表·邻接矩阵·最大团·稠密图
啊董dong28 分钟前
课后作业-2025年11月23号作业
数据结构·c++·算法·深度优先·noi
星释33 分钟前
Rust 练习册 80:Grains与位运算
大数据·算法·rust
zzzsde1 小时前
【C++】C++11(1):右值引用和移动语义
开发语言·c++·算法
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
gfdhy10 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***060110 小时前
SpringMVC 请求参数接收
前端·javascript·算法
一个不知名程序员www11 小时前
算法学习入门---vector(C++)
c++·算法
云飞云共享云桌面11 小时前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑