|
| 1 | +/* |
| 2 | +Set Matrix Zeroes |
| 3 | +================= |
| 4 | +
|
| 5 | +Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix. |
| 6 | +
|
| 7 | +You must do it in place. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] |
| 11 | +Output: [[1,0,1],[0,0,0],[1,0,1]] |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] |
| 15 | +Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] |
| 16 | + |
| 17 | +Constraints: |
| 18 | +m == matrix.length |
| 19 | +n == matrix[0].length |
| 20 | +1 <= m, n <= 200 |
| 21 | +-231 <= matrix[i][j] <= 231 - 1 |
| 22 | + |
| 23 | +Follow up: |
| 24 | +A straightforward solution using O(mn) space is probably a bad idea. |
| 25 | +A simple improvement uses O(m + n) space, but still not the best solution. |
| 26 | +Could you devise a constant space solution? |
| 27 | +*/ |
| 28 | + |
| 29 | +class Solution { |
| 30 | +public: |
| 31 | + void setZeroes(vector<vector<int>>& A) { |
| 32 | + int row = 1, col = 1; |
| 33 | + int n = A.size(), m = A[0].size(); |
| 34 | + |
| 35 | + for(int i = 0; i < n; ++i) { |
| 36 | + for(int j = 0; j < m; ++j) { |
| 37 | + if(A[i][j] == 0) { |
| 38 | + |
| 39 | + if(i == 0) row = 0; |
| 40 | + if(j == 0) col = 0; |
| 41 | + |
| 42 | + if(i != 0 || j != 0) { |
| 43 | + if(j != 0) A[0][j] = 0; |
| 44 | + if(i != 0) A[i][0] = 0; |
| 45 | + } |
| 46 | + |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + for(int i = 1; i < n; ++i) { |
| 52 | + if(A[i][0] == 0) { |
| 53 | + for(int j = 0; j < m; ++j) { |
| 54 | + A[i][j] = 0; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + for(int j = 1; j < m; ++j) { |
| 60 | + if(A[0][j] == 0) { |
| 61 | + for(int i = 0; i < n; ++i) { |
| 62 | + A[i][j] = 0; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + if(row == 0) { |
| 68 | + for(int j = 0; j < m; ++j) { |
| 69 | + A[0][j] = 0; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if(col == 0) { |
| 74 | + for(int i = 0; i < n; ++i) { |
| 75 | + A[i][0] = 0; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +}; |
| 80 | + |
0 commit comments