思路:先遍歷一遍找到0,然后將其他們的行與列分別記下來。接着再把相應行列置0。
public void setZeros(int[][] matrix) { boolean[] row = new boolean[matrix.length]; boolean[] column = new boolean[matrix[0].length]; //確認哪些行哪些列需要置0 for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { row[i] = true; column[j] = true; } } } //置0 for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length; j++) { if (row[i] || column[j]) { matrix[i][j] = 0; } } } }