Problem description
Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Solution Ideas
The difficulty is how to not use the secondary space.
A clever idea is that
1. Using two tag variables, Row0_has_zeros and Col0_has_zeros indicate whether the first row and the first column in the matrix contain 0 elements, respectively;
2. Start the traversal from the inner element of the matrix, and if the matrix element is 0, set the corresponding first row and first column alignment elements to 0;
3. From the inner element of the matrix to start the traversal, the process of traversal, check the corresponding first row and the first column element is 0, if 0, the element is set to 0;
4. Finally, based on the two tag variables, decide whether you need to set all the elements of the first row and the first column to 0.
The time complexity is O (n^2) and the space complexity is O (1).
Program
public class Solution {public void Setzeroes (int[][] matrix) { if (Matrix = = NULL | | matrix.length = = 0 | | matrix [0].length = = 0) {return;} Boolean Row0_has_zeros = False;boolean Col0_has_zeros = false;for (int i = 0; i < matrix[0].length; i++) {if (matrix[0] [i] = = 0) {Row0_has_zeros = True;break;}} for (int i = 0; i < matrix.length; i++) {if (matrix[i][0] = = 0) {Col0_has_zeros = True;break;}} for (int i = 1, i < matrix.length; i++) {for (int j = 1; j < Matrix[0].length; J + +) {if (matrix[i][j] = = 0) {matrix[ 0][J] = 0;matrix[i][0] = 0;}}} for (int i = 1, i < matrix.length; i++) {for (int j = 1; j < Matrix[0].length; J + +) {if (matrix[0][j] = = 0 | | matrix I [0] = = 0) {Matrix[i][j] = 0;}}} if (Row0_has_zeros) {for (int i = 0; i < matrix[0].length; i++) {matrix[0][i] = 0;}} if (Col0_has_zeros) {for (int i = 0; i < matrix.length; i++) {matrix[i][0] = 0;}}}
Set Matrix Zeros