|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. |
| 5 | + * <p/> |
| 6 | + * Follow up: |
| 7 | + * Did you use extra space? |
| 8 | + * A straight forward solution using O(mn) space is probably a bad idea. |
| 9 | + * A simple improvement uses O(m + n) space, but still not the best solution. |
| 10 | + * Could you devise a constant space solution? |
| 11 | + */ |
| 12 | +public class SetMartixZero { |
| 13 | + public static void main(String[] args) { |
| 14 | + int[][] matrix = new int[][]{ |
| 15 | + {1, 2, 3, 5}, |
| 16 | + {2, 4, 0, 1}, |
| 17 | + {2, 4, 2, 1}, |
| 18 | + {0, 4, 2, 1}, |
| 19 | + }; |
| 20 | + |
| 21 | + System.out.println(Arrays.deepToString(matrix)); |
| 22 | + setMatrixZero(matrix); |
| 23 | + System.out.println(Arrays.deepToString(matrix)); |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + // do it in place |
| 28 | + // use first row/col to record zero flag |
| 29 | + public static void setMatrixZero(int[][] m) { |
| 30 | + if (m.length <= 0) return; |
| 31 | + int row = m.length; |
| 32 | + int col = m[0].length; |
| 33 | + |
| 34 | + boolean firstRowZero = false; |
| 35 | + boolean firstColZero = false; |
| 36 | + |
| 37 | + for (int j = 0; j < col; j++) { |
| 38 | + if (m[0][j] == 0) { |
| 39 | + firstRowZero = true; |
| 40 | + break; |
| 41 | + } |
| 42 | + } |
| 43 | + for (int i = 0; i < row; i++) { |
| 44 | + if (m[i][0] == 0) { |
| 45 | + firstColZero = true; |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + for (int i = 1; i < row; i++) { |
| 51 | + for (int j = 1; j < col; j++) { |
| 52 | + if (m[i][j] == 0) { |
| 53 | + // set zero flag on the first row/col |
| 54 | + m[0][j] = 0; |
| 55 | + m[i][0] = 0; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // set zero based on zero flag |
| 61 | + for (int i = 1; i < row; i++) { |
| 62 | + for (int j = 1; j < col; j++) { |
| 63 | + if (m[0][j] == 0 || m[i][0] == 0) { |
| 64 | + m[i][j] = 0; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + if (firstRowZero) { |
| 70 | + for (int j = 0; j < col; j++) { |
| 71 | + m[0][j] = 0; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + if (firstColZero) { |
| 76 | + for (int i = 0; i < col; i++) { |
| 77 | + m[i][0] = 0; |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return; |
| 82 | + } |
| 83 | +} |
0 commit comments