|
| 1 | +package Blind75; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/* |
| 6 | + * Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. |
| 7 | + */ |
| 8 | +public class Lt73 { |
| 9 | + public static void main(String[] args) { |
| 10 | + |
| 11 | + } |
| 12 | + |
| 13 | + //solution is in O(1) |
| 14 | + public void setZeroes(int[][] matrix) { |
| 15 | + int m= matrix.length; //length of the rows |
| 16 | + int n= matrix[0].length; //length of the columns |
| 17 | + int k=0; |
| 18 | + |
| 19 | + //does first row have zero? |
| 20 | + while(k < n && matrix[0][k] !=0){ |
| 21 | + k++; |
| 22 | + } |
| 23 | + |
| 24 | + //use first row/column as a marker, scan the matrix |
| 25 | + for(int i=0; i< m; i++){ |
| 26 | + for(int j=0; j<n; j++){ |
| 27 | + if(matrix[i][j]==0){ |
| 28 | + matrix[0][j] =matrix[i][0]=0; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + //set the zeros |
| 34 | + for(int i=1; i<m; i++){ |
| 35 | + for(int j=n-1; j>=0; j--){ |
| 36 | + if(matrix[0][j] == 0 || matrix[i][0]==0){ |
| 37 | + matrix[i][j]=0; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + //set the zeros for the first row |
| 42 | + if(k<n){ |
| 43 | + Arrays.fill(matrix[0], 0); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments