1. 程式人生 > >19.2.13 [LeetCode 73] Set Matrix Zeroes

19.2.13 [LeetCode 73] Set Matrix Zeroes

event span lee display 包含 none forward 特殊情況 imp

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]
]

Follow up:

  • 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?

題意

矩陣中把所有包含0的行和列全部歸0

題解

技術分享圖片
 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int
>>& matrix) { 4 int m = matrix.size(), n = matrix[0].size(); 5 bool row = false, colum = false; 6 for (int i = 0; i < m; i++) 7 for (int j = 0; j < n; j++) { 8 if (matrix[i][j] == 0) { 9 if (i == 0)row = true
; 10 if (j == 0)colum = true; 11 if(i!=0) 12 matrix[i][0] = 0; 13 if(j!=0) 14 matrix[0][j] = 0; 15 } 16 } 17 for (int i = 1; i < m; i++) 18 for (int j = 1; j < n; j++) 19 if (!matrix[i][0] || !matrix[0][j]) 20 matrix[i][j] = 0; 21 if (colum) { 22 for (int i = 0; i < m; i++) 23 matrix[i][0] = 0; 24 } 25 if(row){ 26 for (int j = 0; j < n; j++) 27 matrix[0][j] = 0; 28 } 29 } 30 };
View Code

我一開始都沒get到點在哪,試錯之後才發現難點在哪……稍微用倆bool對 matrix[0][0] 的特殊情況處理一下就可以了

19.2.13 [LeetCode 73] Set Matrix Zeroes