【leetcode100】矩阵置零

1、题目描述

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用原地算法。

示例 1:

复制代码
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

2、初始思路

2.1 思路1

先找出所有0的横纵坐标,然后遍历置零。

复制代码
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        all_i = []
        all_j = []
        m, n = len(matrix), len(matrix[0])
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    if i not in all_i:
                        all_i.append(i)
                    if j not in all_j:
                        all_j.append(j)
        #print(all_i)
        for i in all_i:
            for j in range(n):
                matrix[i][j] = 0
        for j in all_j:
            for i in range(m):
                matrix[i][j] = 0
        return matrix

2.2 思路2

通过设置false来判断0的存在

复制代码
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        m, n = len(matrix), len(matrix[0])
        m_0 = m * [False]
        n_0 = n * [False]
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    m_0[i] = True
                    n_0[j] = True
        for i in range(m):
            for j in range(n):
                if m_0[i] or n_0[j]:
                    matrix[i][j] = 0

3、总结

1、矩阵的行列计算为

复制代码
行
m = len(matrix)
列
n = len(matrix[0])

2、python中False和True首字母要大写

相关推荐
用户8356290780514 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
爱理财的程序媛6 小时前
openclaw 盯盘实践
算法
markfeng86 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi6 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee7 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay7 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤7 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean8 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽9 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi