public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean[] rowzero = new boolean[rows];
boolean[] colzero = new boolean[cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matrix[r][c] == 0) {
rowzero[r] = true;
colzero[c] = true;
}
}
}
for (int r = 0; r < rows; r++) {
if (rowzero[r]) {
for (int c = 0; c < cols; c++) {
matrix[r][c] = 0;
}
}
}
for (int c = 0; c < cols; c++) {
if (colzero[c]) {
for (int r = 0; r < rows; r++) {
matrix[r][c] = 0;
}
}
}
}
int rows = matrix.length;
int cols = matrix[0].length;
boolean[] rowzero = new boolean[rows];
boolean[] colzero = new boolean[cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matrix[r][c] == 0) {
rowzero[r] = true;
colzero[c] = true;
}
}
}
for (int r = 0; r < rows; r++) {
if (rowzero[r]) {
for (int c = 0; c < cols; c++) {
matrix[r][c] = 0;
}
}
}
for (int c = 0; c < cols; c++) {
if (colzero[c]) {
for (int r = 0; r < rows; r++) {
matrix[r][c] = 0;
}
}
}
}
- Variable naming.
flagArris a matrix and not an (1 diemensional) array. But it would be more helpful to name it to what it is used for rather than what it is. How aboutzerosFound?iandjI would either name asxandyorcolandrow. - Spacing. It's not wrong to have a bit of more space in your lines. Use spaces around
<and=and before{etc. Here's what parts of your code looks like when I press Ctrl + Shift + F in Eclipse (which is a key shortcut for auto formatting).
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == 0) { flagArr[i][j] = true; } } }
No comments:
Post a Comment