【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首字母要大写

相关推荐
IT观测6 分钟前
创想三维携AI教育全矩阵亮相第87届教装展,构建3D打印教育新范式
人工智能·3d·矩阵
xcbrand32 分钟前
快消品品牌策划公司哪家好
大数据·人工智能·python
踩坑记录37 分钟前
leetcode hot100 118. 杨辉三角 easy 动态规划
leetcode·动态规划
小O的算法实验室41 分钟前
2026年ESWA,自适应基于排序的协同进化学习粒子群算法+边缘计算服务器部署,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
2301_8038756142 分钟前
Python怎么计算NumPy数组的切比雪夫距离_使用abs与max求解
jvm·数据库·python
Dxy12393102161 小时前
Python使用XPath定位元素:动态计算与函数调用
开发语言·python
cpp_25011 小时前
P1832 A+B Problem(再升级)
数据结构·c++·算法·动态规划·题解·洛谷·背包dp
qq_349317481 小时前
CSS如何实现Bootstrap进度条自定义动画_利用keyframe关键帧
jvm·数据库·python
wltx16881 小时前
海外版GEO优化适合耳机出口吗?
人工智能·python
vonlycn1 小时前
PaddleDetection转ONNX 填坑
python·onnx·paddledetection