LeetCode 73 Set Matrix Zeroes
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?
一開始想到了空間O(m + n)的算法,用一個數組arr[m+n]記錄某行或者某列是否需要設為0,遍歷一遍數組,若num[i][j]==0,則對應的賦值arr[i]=0,arr[m+j]=0即可。
沒想到constant的方法,上網搜一番之后發現:
沒有必要新開一個arr[m+n]數組,其實遍歷num[i][j]==0后,直接將num[i][0]與num[0][j]設為0即可~~確實啊!!!
不過對于首行和首列,這樣直接改變它們的值會影響它們原本的值,而首行與首列是否set為0又是由它們原本的值決定的,因此一開始先掃一遍首行與首列,確定它們是否需要set,再掃描i=[2...m]與j=[2...n],判斷其他行與列。
代碼:
public void setZeroes(int[][] matrix) {
if (matrix.length == 0) return;
int m = matrix.length, n = matrix[0].length;
boolean row = false, col = false;
// Check first row & col
if (matrix[0][0] == 0) {
row = true;
col = true;
} else {
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
col = true;
matrix[0][0] = 0;
break;
}
}
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
row = true;
matrix[0][0] = 0;
break;
}
}
}
// Check other rows & cols
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;
}
}
}
// Assign rows
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < n; j++) matrix[i][j] = 0;
}
}
// Assign cols
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < m; i++) matrix[i][j] = 0;
}
}
// Assign first row & col
if (col) {
for (int i = 1; i < m; i++) matrix[i][0] = 0;
}
if (row) {
for (int j = 1; j < n; j++) matrix[0][j] = 0;
}
}