zoukankan      html  css  js  c++  java
  • 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.
    Follow up:
    Did you use extra space?
    A straight forward solution using O(mn) space is probably a bad idea.
    A simple improvement uses O(m + n) space, but still not the best solution.
    Could you devise a constant space solution?

    Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.

     1 class Solution {
     2 public:
     3     void setZeroes(vector<vector<int> > &matrix) {
     4         if(matrix.empty()) return;
     5         int R = matrix.size();
     6         int C = matrix[0].size();
     7         bool firstRowZero = false;
     8         bool firstColZero = false;
     9         
    10         for(int j = 0; j < C; j++) {
    11             if(matrix[0][j] == 0) {
    12                 firstRowZero = true;
    13                 break;
    14             }
    15         }
    16         
    17         for(int i = 0; i < R; i++) {
    18             if(matrix[i][0] == 0) {
    19                 firstColZero = true;
    20                 break;
    21             }
    22         }
    23         
    24         for(int i = 1; i < R; i++) {
    25             for(int j = 1; j < C; j++) {
    26                 if(matrix[i][j] == 0) {
    27                     matrix[i][0] = 0;
    28                     matrix[0][j] = 0;
    29                 }
    30             }
    31         }
    32         
    33         for(int i = 1; i < R; i++)
    34             if(matrix[i][0] == 0)
    35                 for(int j = 1; j < C; j++)
    36                     matrix[i][j] = 0;
    37         
    38         for(int j = 1; j < C; j++)
    39             if(matrix[0][j] == 0)
    40                 for(int i = 1; i < R; i++)
    41                     matrix[i][j] = 0;
    42                     
    43         if(firstRowZero)
    44             for(int j = 0; j < C; j++)
    45                 matrix[0][j] = 0;
    46                 
    47         if(firstColZero)
    48             for(int i = 0; i < R; i++)
    49                 matrix[i][0] = 0;
    50     }
    51 };
  • 相关阅读:
    【转】一个URL编码和解码的C++类
    ofstream的问题
    如何解决"应用程序无法启动,因为应用程序的并行配置不正确"问题(转载)
    最小生成树 prim & kruskal
    【2018百度之星资格赛】F 三原色图
    cout 按进制数出
    【2018百度之星资格赛】 A 问卷调查
    银河英雄传说
    读入读出挂!!
    关押罪犯
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3651166.html
Copyright © 2011-2022 走看看