Write an algorithm such that if an element in an MxN matrix is 0, its
entire rowand column are set to 0.
1 public static void matrixZero(int[][] matrix) { 2 if (matrix.length == 0 || matrix[0].length == 0) 3 return; 4 5 int m = matrix.length; 6 int n = matrix[0].length; 7 boolean rowZero = false; 8 boolean colZero = false; 9 10 // save first row and first col 11 for (int i = 0; i < m; i++) 12 if (matrix[i][0] == 0) 13 rowZero = true; 14 for (int i = 0; i < n; i++) 15 if (matrix[0][i] == 0) 16 colZero = true; 17 18 for (int i = 0; i < m; i++) { 19 for (int j = 0; j < n; j++) { 20 if (matrix[i][j] == 0) { 21 matrix[i][0] = 0; 22 matrix[0][j] = 0; 23 } 24 } 25 } 26 27 for (int i = 1; i < m; i++) { 28 if (matrix[i][0] == 0) 29 for (int j = 1; j < n; j++) { 30 matrix[i][j] = 0; 31 } 32 } 33 34 for (int i = 1; i < n; i++) { 35 if (matrix[0][i] == 0) 36 for (int j = 1; j < m; j++) { 37 matrix[j][i] = 0; 38 } 39 } 40 41 if (rowZero) { 42 for (int i = 0; i < m; i++) 43 matrix[i][0] = 0; 44 } 45 46 if (colZero) { 47 for (int i = 0; i < n; i++) 48 matrix[0][i] = 0; 49 } 50 }