Given a m x n matrix, 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.
Could you devise a constant space solution?
Subscribe to see which companies asked this question
1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return; 4 int m = matrix.length, n = matrix[0].length; 5 int[] rowflag = new int[m]; 6 int[] colflag = new int[n]; 7 for(int i = 0; i < m; i++){ 8 for(int j = 0; j < n; j++){ 9 if(matrix[i][j] == 0){ 10 rowflag[i] = 1; 11 colflag[j] = 1; 12 } 13 } 14 } 15 for(int i = 0; i < m; i++){ 16 if(rowflag[i] == 1){ 17 for(int j = 0; j < n; j++){ 18 matrix[i][j] = 0; 19 } 20 } 21 } 22 for(int i = 0; i < n; i++){ 23 if(colflag[i] == 1){ 24 for(int j = 0; j < m; j++){ 25 matrix[j][i] = 0; 26 } 27 } 28 } 29 } 30 }