Given a m x n matrix, if an element was 0, set its entire row and column to 0. Do it on 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 is not the best solution.
Could you devise a constant space solution?
public class Solution {public void setzeroes (int[][] matrix) {int m=matrix.length; if (m==0) return; int n=matrix[0].length; if (n==0) return; Boolean prezeros=false; Boolean curzeros=false; for (int i=0;i<m;i++) {//test If this row has zeros. for (int j=0;j<n;j++) {if (matrix[i][j]==0) {for (int k=0;k& lt;i;k++) matrix[k][j]=0; Curzeros=true; }}//fill the zeros along Coloum. if (i>0) {for (int j=0;j<n;j++) {if (matrix[i-1][j]==0) {matrix[i][j]=0; }}}//if pre row have zeros, fill zeros with that row. if (Prezeros) {for (int J=0;j<n;j++) {matrix[i-1][j]=0; }} Prezeros=curzeros; Curzeros=false; } if (Prezeros) {for (int j=0;j<n;j++) {matrix[m-1][j]=0; } } }}
Set the row and column of the element with value 0 in the matrix to 0, in-place O (1) Space O (MN) time