Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
public class Solution { public void setZeroes(int[][] matrix) { // Start typing your Java solution below // DO NOT write main() function int row = matrix.length; if(row == 0 )return; int col = matrix[0].length; boolean firstrow = false; boolean firstcol = false; for(int i = 0 ; i < row ; i++){ if(matrix[i][0] == 0) firstrow = true; break; } for(int i = 0 ; i < col ; i++){ if(matrix[0][i] == 0) firstcol = true; break; } for(int i = 1 ; i< row; i++){ for(int j = 1; j < col ; j++){ if(matrix[i][j] ==0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int i = 1 ; i< row; i++){ for(int j = 1; j < col ; j++){ if(matrix[i][0] ==0||matrix[0][j]==0){ matrix[i][j] = 0; } } } if(firstrow){ for(int i = 0 ; i < col; i++) matrix[0][i] = 0; } if(firstcol){ for(int i = 0 ; i < row; i++) matrix[i][0] = 0; } } }
public class Solution { public void setZeroes(int[][] matrix) { // Note: The Solution object is instantiated only once and is reused by each test case. int[] row = new int[matrix.length]; int[] col = new int[matrix[0].length]; for(int i = 0 ; i < row.length ; i++){ for(int j = 0; j < col.length; j++){ if(matrix[i][j] == 0){ row[i] = 1; col[j] = 1; } } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(row[i] == 1 || col[j] == 1){ matrix[i][j] = 0; } } } } }