# 73. Set Matrix Zeroes (Medium)

https://leetcode.com/problems/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]
]
```

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

## Solutions

``````class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}

int tmp = 1690664872;

int row = matrix.length;
int col = matrix.length;

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] != 0) {
continue;
}

// To reach here, matrix[i][j] is 0

// do not turn values on same row/column to 0, it will bring in consequent
// influence for followup processing.

for (int x = 0; x < row; x++) {
// do not modify the cell if original value is 0
if (matrix[x][j] == 0) {
continue;
}
matrix[x][j] = tmp;
}

for (int y = 0; y < col; y++) {
// do not modify the cell if original value is 0
if (matrix[i][y] == 0) {
continue;
}
matrix[i][y] = tmp;
}
}
}

// reset the turned values to 0
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] == tmp) {
matrix[i][j] = 0;
}
}
}
}
}
``````