73. Set Matrix Zeroes - jiejackyzhang/leetcode-note GitHub Wiki
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
使用first column来记录每一行的状态,first row来记录每一列的状态。 若matrix[i][j]==0,则令matrix[i][0] = matrix[0][j] = 0。 但是第一行和第一列的状态会使用同一个cell,即matrix[0][0],因此我们令其记录第一行的状态,设置boolean变量col0来记录第一列的状态。
一共两次扫描matrix,第一次top-down来设置状态,第二次bottom-up来set zeroes。 之所以bottom-up right-left的顺序来set zeroes,是要保证状态位是最后改变的。
public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int m = matrix.length;
int n = matrix[0].length;
boolean col0 = false;
for(int i = 0; i < m; i++) {
if(matrix[i][0] == 0) col0 = true;
for(int j = 1; j < n; j++) {
if(matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i = m-1; i >= 0; i--) {
for(int j = n-1; j >= 1; j--) {
if(matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
if(col0) matrix[i][0] = 0;
}
}
}