|
| 1 | +package com.ctci.arraysandstrings; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Write an algorithm such that if an element in an MxN matrix is 0, its entire row |
| 8 | + * and column are set to 0. |
| 9 | + * |
| 10 | + * @author rampatra |
| 11 | + * @since 2019-01-20 |
| 12 | + */ |
| 13 | +public class ZeroMatrix { |
| 14 | + |
| 15 | + private static void zeroMatrix(int[][] matrix) { |
| 16 | + // keep count of which rows and columns have a number zero |
| 17 | + List<Integer> rowsToZero = new ArrayList<>(); |
| 18 | + List<Integer> colsToZero = new ArrayList<>(); |
| 19 | + |
| 20 | + for (int i = 0; i < matrix.length; i++) { |
| 21 | + for (int j = 0; j < matrix[0].length; j++) { |
| 22 | + if (matrix[i][j] == 0) { |
| 23 | + rowsToZero.add(i); |
| 24 | + colsToZero.add(j); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + makeRowColumnZero(matrix, rowsToZero, colsToZero); |
| 30 | + } |
| 31 | + |
| 32 | + private static void makeRowColumnZero(int[][] matrix, List<Integer> rows, List<Integer> cols) { |
| 33 | + for (int row : rows) { |
| 34 | + // make entire row zero |
| 35 | + for (int c = 0; c < matrix[0].length; c++) { |
| 36 | + matrix[row][c] = 0; |
| 37 | + } |
| 38 | + } |
| 39 | + for (int col : cols) { |
| 40 | + // make entire column zero |
| 41 | + for (int r = 0; r < matrix.length; r++) { |
| 42 | + matrix[r][col] = 0; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static void printMatrix(int[][] matrix) { |
| 48 | + for (int i = 0; i < matrix.length; i++) { |
| 49 | + for (int j = 0; j < matrix[0].length; j++) { |
| 50 | + System.out.print(matrix[i][j]); |
| 51 | + if (j + 1 >= matrix[0].length) { |
| 52 | + System.out.println(); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) { |
| 59 | + int[][] m = new int[][]{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; |
| 60 | + printMatrix(m); |
| 61 | + zeroMatrix(m); |
| 62 | + System.out.println("---"); |
| 63 | + printMatrix(m); |
| 64 | + System.out.println("---"); |
| 65 | + m = new int[][]{{1, 0, 2}, {3, 4, 5}, {6, 7, 8}}; |
| 66 | + printMatrix(m); |
| 67 | + zeroMatrix(m); |
| 68 | + System.out.println("---"); |
| 69 | + printMatrix(m); |
| 70 | + System.out.println("---"); |
| 71 | + m = new int[][]{{1, 2, 0}, {3, 4, 5}, {6, 7, 8}}; |
| 72 | + printMatrix(m); |
| 73 | + zeroMatrix(m); |
| 74 | + System.out.println("---"); |
| 75 | + printMatrix(m); |
| 76 | + System.out.println("---"); |
| 77 | + } |
| 78 | +} |
0 commit comments