LeetCode, leetcodeoj
Question:
GivenMXNMatrix, 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.
Cocould you devise a constant space solution?
Ideas:
1) O (mn) solution, copy a matrix, and set each element of the original matrix against this matrix.
2) O (m + n) solution. There are two one-dimensional Boolean arrays Rows and Columns. The sizes are m and n. If the element (I, j) is 0, set Rows [I] to true and Columns [j] to true. Then, set each row and column to 0 based on the values in Rows and Columns.
3) based on method 2, the first and first columns of matrix are used to indicate whether the corresponding columns and rows are 0, but at this time, we need to perform special processing on the first row and the first column, so we can use two Boolean variables to deal with it.
package array;public class SetMatrixZeroes { public void setZeroes(int[][] matrix) { boolean firstRow = false; boolean firstColumn = false; int m = matrix.length; int n = matrix[0].length; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { if (i == 0) firstRow = true; if (j == 0) firstColumn = true; matrix[i][0] = matrix[0][j] = 0; } } } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; } } if (firstRow) { for (int i = 0; i < n; ++i) matrix[0][i] = 0; } if (firstColumn) { for (int i = 0; i < m; ++i) matrix[i][0] = 0; } } public static void main(String[] args) { // TODO Auto-generated method stub int[][] matrix = { { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } }; SetMatrixZeroes s = new SetMatrixZeroes(); s.setZeroes(matrix); }}