LeetCode73.矩阵置零/面试题 01.08. 零矩阵
Question
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
Example
Example 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Idea
Solution1:辅助数组
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> r(m), c(n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!matrix[i][j]) {
r[i] = c[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (r[i] || c[j]) {
matrix[i][j] = 0;
}
}
}
}
};
Solution2:第一行第一列作为辅助数组
//代码存在优化空间,此处便于理解未做
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size(), fm = 0, fn = 0;
//第一行是否有0判断
for(int i = 0; i < n; i++){
if(matrix[0][i] == 0){
fn = 1;
break;
}
}
//第一列是否有0判断
for(int i = 0; i < m; i++){
if(matrix[i][0] == 0){
fm = 1;
break;
}
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if(matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// 筛选第一行中有0 元素置列为0
for(int j = 1; j < n; j++){
if(matrix[0][j] == 0){
for(int i = 1; i < m; i++){
matrix[i][j] = 0;
}
}
}
// 筛选第一列中有0 元素置行为0
for(int i = 1; i < m; i++){
if(matrix[i][0] == 0){
for(int j = 1; j < n; j++){
matrix[i][j] = 0;
}
}
}
if(fm){
for(int i = 0; i < m; i++){
matrix[i][0] = 0;
}
}
if(fn){
for(int i = 0; i < n; i++){
matrix[0][i] = 0;
}
}
}
};
Solution3:最后一行作为辅助数组
//代码存在优化空间,此处便于理解未做
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size(), f = 0, tmp = 0;
//最后一行是否有0判断
for(int i = 0; i < n; i++){
if(matrix[m-1][i] == 0){
f = 1;
break;
}
}
for(int i = 0; i < m - 1; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 0){
matrix[m-1][j] = 0;
tmp = 1;
}
if(tmp && j == n-1){
tmp = 0;
for(int k = 0; k < n; k++){
matrix[i][k] = 0;
}
}
}
}
for(int i = 0; i < n; i++){
if(matrix[m-1][i] == 0){
for(int j = 0; j < m - 1; j++){
matrix[j][i] = 0;
}
}
}
if(f){
for(int i = 0; i < n; i++){
matrix[m-1][i] = 0;
}
}
}
};