| 16 | } |
| 17 | |
| 18 | static void setZeroes(int[][] matrix) { |
| 19 | boolean firstrow = false; |
| 20 | |
| 21 | //checking for zero element and storing info in the matrix itself (in the first row and column). |
| 22 | for (int i = 0; i < matrix.length; i++) { |
| 23 | for (int j = 0; j < matrix[i].length; j++) { |
| 24 | if (matrix[i][j] == 0) { |
| 25 | if (i == 0) { |
| 26 | firstrow = true; |
| 27 | } else { |
| 28 | matrix[i][0] = 0; |
| 29 | } |
| 30 | matrix[0][j] = 0; |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // iterating from bottom right to top left and converting to zero. |
| 36 | for (int i = matrix.length - 1; i >= 0; i--) { |
| 37 | for (int j = matrix[i].length - 1; j >= 0; j--) { |
| 38 | if (i == 0 && firstrow) { |
| 39 | matrix[i][j] = 0; |
| 40 | } else if (i != 0 && (matrix[i][0] == 0 || matrix[0][j] == 0)) { |
| 41 | matrix[i][j] = 0; |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // to print out the matrix |
| 48 | public static void print2D(int mat[][]) { |