【枚举】枚举所有位置的数,如果是0,就把当前行和列的元素置为0,但是需要用一个标记来标记这个位置是被置的0,而不是原来就是0。
class Solution {
// 7:22 9
// 枚举
int[][] matrix, visit;
int m, n;
public void clear(int x, int y) {
for (int i = 0; i < m; i++) {
if (matrix[i][y] != 0) {
matrix[i][y] = 0;
visit[i][y] = 1;
}
}
for (int j = 0; j < n; j++) {
if (matrix[x][j] != 0) {
matrix[x][j] = 0;
visit[x][j] = 1;
}
}
}
public void setZeroes(int[][] matrix) {
m = matrix.length; n = matrix[0].length;
this.matrix = matrix;
this.visit = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visit[i][j] == 1) continue;
if (matrix[i][j] == 0) {
clear(i, j);
}
}
}
}
}
【优化】用一个行数组和一个列数组来标记更省空间。
class Solution {
// 7:38 4
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
boolean[] row = new boolean[m], col = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (row[i] || col[j]) matrix[i][j] = 0;
}
}
}
}