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:
矩阵中把所有包含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 };
我一开始都没get到点在哪,试错之后才发现难点在哪……稍微用俩bool对 matrix[0][0] 的特殊情况处理一下就可以了
19.2.13 [LeetCode 73] Set Matrix Zeroes
原文:https://www.cnblogs.com/yalphait/p/10371671.html