55. Set Matrix Zeroes

时间:2021-12-11 09:10:57

Set Matrix Zeroes

(Link: https://oj.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.

click to show follow up.

Follow up:

Did you use extra space? 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 元素,分别将其投影在记下的行和列上(做标记)。遍历之后,对于所有行中的标记,将其所在列都置为 0; 对于所有列中标记,将其所在行都置为 0. (最后置标记的行和列为 0. 可含在上述步骤) 时间: O(n2), 空间 : O(1)

class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(!matrix.size() || !matrix[0].size()) return;
const int INF = 1001;
int row = matrix.size(), col = matrix[0].size();
int u = -1, v = -1;
for(int r = 0; r < row; ++r)
for(int c = 0; c < col; ++c) {
if(matrix[r][c] == 0) {
if(u == -1) { u = r, v = c; continue; }
matrix[u][c] = INF;
matrix[r][v] = INF;
}
}
if(u == -1) return;
if(matrix[u][v] == INF) matrix[u][v] = 0;
for(int c = 0; c < col; ++c) {
if(matrix[u][c] == INF) {
for(int i = 0; i < row; ++i) matrix[i][c] = 0;
} else matrix[u][c] = 0;
}
for(int r = 0; r < row; ++r) {
if(matrix[r][v] == INF) {
for(int j = 0; j < col; ++j) matrix[r][j] = 0;
} else matrix[r][v] = 0;
}
}
};