Problem Description:
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?
Analysis:
这道题要求是有O(1)的空间,所以必须在原有数组上直接进行操作,这道题中我们使用变量flag来处理边界问题,然后用边界的数组来保存每行和每列的状态。代码如下:
Code:
class Solution {
public void setZeroes(int[][] matrix) {
int r = matrix.length;
if(r < 1)
return;
int c = matrix[0].length;
int flag = 0;
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
if(matrix[i][j] == 0) {
if(i == 0 && j== 0) {
flag = 3;
continue;
}
if(i == 0) {
matrix[i][0] = 0;
if(flag == 0) {
flag = 1;
} else if(flag == 2) {
flag = 3;
}
} else if(j == 0) {
matrix[0][j] = 0;
if(flag == 0) {
flag = 2;
} else if(flag == 1) {
flag = 3;
}
} else {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
}
for(int i = 1; i < r; i++) {
if(matrix[i][0] == 0) {
for(int j = 1; j < c; j++) {
matrix[i][j] = 0;
}
}
}
for(int i = 1; i < c; i++) {
if(matrix[0][i] == 0) {
for(int j = 1; j < r; j++) {
matrix[j][i] = 0;
}
}
}
if(flag == 1) {
for(int i = 0; i < c; i++) {
matrix[0][i] = 0;
}
} else if(flag == 2) {
for(int i = 0; i < r; i++) {
matrix[i][0] = 0;
}
} else if(flag == 3) {
for(int i = 0; i < c; i++) {
matrix[0][i] = 0;
}
for(int i = 0; i < r; i++) {
matrix[i][0] = 0;
}
}
}
}