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?
题解:
class Solution {
static void signToMinus(int n, int m, vector<vector<int>>& matrix, int x, int y) {
for (int i = 0; i < m; i++) {
if (matrix[x][i] != 0) {
matrix[x][i] = 10000;
}
}
for (int i = 0; i < n; i++) {
if (matrix[i][y] != 0) {
matrix[i][y] = 10000;
}
}
}
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
signToMinus(n, m, matrix, i, j);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 10000) {
matrix[i][j] = 0;
}
}
}
}
};