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?
Https://oj.leetcode.com/problems/set-matrix-zeroes/
Best Practice: traverse the two-dimensional array first, and then use the first row and the first column as a marker to determine whether the entire row should be set to 0. Two Boolean records are used for the first row and the first column.
public class Solution { public void setZeroes(int[][] matrix) { if(matrix==null||matrix.length==0||matrix[0].length==0) return; int m=matrix.length; int n=matrix[0].length; int i,j; boolean isFirstRowZero=false; boolean isFirstColZero=false; for(i=0;i<m;i++){ if(matrix[i][0]==0){ isFirstColZero=true; break; } } for(i=0;i<n;i++){ if(matrix[0][i]==0){ isFirstRowZero=true; break; } } for(i=0;i<m;i++){ for(j=0;j<n;j++){ if(matrix[i][j]==0){ matrix[0][j]=0; matrix[i][0]=0; } } } for(i=1;i<m;i++){ if(matrix[i][0]==0){ for(j=0;j<n;j++) matrix[i][j]=0; } } for(i=1;i<n;i++){ if(matrix[0][i]==0){ for(j=0;j<m;j++) matrix[j][i]=0; } } if(isFirstRowZero){ for(i=0;i<n;i++) matrix[0][i]=0; } if(isFirstColZero){ for(i=0;i<m;i++) matrix[i][0]=0; } return; }}View code
Refer:
Http://jane4532.blogspot.com/2013/09/set-matrix-zeroleetcode.html