题目:
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(m n) 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 {
public:
void setZeroes(vector<vector<int> > &matrix) {
const int row = matrix.size();
const int col = matrix[0].size();
bool row_flg = false, col_flg = false;
//判断第一行和第一列是否有零,防止被覆盖
for (int i = 0; i < row; i++)
if (0 == matrix[i][0]) {
col_flg = true;
break;
}
for (int i = 0; i < col; i++)
if (0 == matrix[0][i]) {
row_flg = true;
break;
}
//遍历矩阵,用第一行和第一列记录0的位置
for (int i = 1; i < row; i++)
for (int j = 1; j < col; j++)
if (0 == matrix[i][j]) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
//根据记录清零
for (int i = 1; i < row; i++)
for (int j = 1; j < col; j++)
if (0 == matrix[i][0] || 0 == matrix[0][j])
matrix[i][j] = 0;
//最后处理第一行
if (row_flg)
for (int i = 0; i < col; i++)
matrix[0][i] = 0;
if (col_flg)
for (int i = 0; i < row; i++)
matrix[i][0] = 0;
}
};