zoukankan      html  css  js  c++  java
  • 73. Set Matrix Zeroes

     

    Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

    Example 1:

    Input: 
    [
      [1,1,1],
      [1,0,1],
      [1,1,1]
    ]
    Output: 
    [
      [1,0,1],
      [0,0,0],
      [1,0,1]
    ]
    

    Example 2:

    Input: 
    [
      [0,1,2,0],
      [3,4,5,2],
      [1,3,1,5]
    ]
    Output: 
    [
      [0,0,0,0],
      [0,4,5,0],
      [0,3,1,0]
    ]




    思路:
    用矩阵的第一行存储,哪一列需要置0
    用矩阵的第一列存储,哪一行需要置0
     1 class Solution {
     2 public:
     3     void setZeroes(vector<vector<int>>& matrix) {
     4         int rows = matrix.size();
     5         int cols = matrix[0].size();
     6         int col0=1,row0=1;
     7 
     8         
     9         for(int i = 0;i<rows;i++)
    10             if(matrix[i][0]==0)col0=0;
    11         
    12         for(int j = 0;j<cols;j++)
    13             if(matrix[0][j]==0)row0=0;
    14         
    15         
    16         
    17         for(int i = 1;i<rows;i++)
    18             for(int j = 1;j<cols;j++)
    19                 if(matrix[i][j]==0){
    20                     matrix[0][j] = 0;
    21                     matrix[i][0] = 0;
    22                 }
    23     
    24         
    25         
    26         for(int i = 1;i<rows;i++)
    27               for(int j = 1;j<cols;j++)
    28                 if(matrix[i][0]==0||matrix[0][j]==0)
    29                     matrix[i][j]=0;
    30         
    31         if(col0==0){
    32             for(int i = 0;i<rows;i++)
    33                 matrix[i][0] = 0;
    34         }
    35         if(row0==0){
    36         for(int j = 0;j<cols;j++)
    37             matrix[0][j]= 0 ;
    38         }
    39         
    40     }
    41 };
  • 相关阅读:
    PS初步学习经验心得记录
    css第四天--复合选择器和样式三大特性
    css第三天--盒子模型
    html第二天--表单控件和表格
    css第二天--字体属性和文本属性
    vue计算属性(computed)
    ant-input的使用
    js-split() 方法
    设计转到前端开发
    $set
  • 原文地址:https://www.cnblogs.com/zle1992/p/10240077.html
Copyright © 2011-2022 走看看