|
| 1 | +package crackingTheCodingInterview.chap1; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +/** |
| 9 | + * ### Zero Matrix: |
| 10 | + * Write an algorithm such that if an element in an MxN matrix is 0, |
| 11 | + * its entire row and column are set to 0. |
| 12 | + */ |
| 13 | +public class ZeroMatrix { |
| 14 | + |
| 15 | + // Test Driven Development by Aseem Jain |
| 16 | + @Test |
| 17 | + public void test() { |
| 18 | + |
| 19 | + int[][] matrix = { |
| 20 | + {1, 2, 3}, |
| 21 | + {1, 2, 3}, |
| 22 | + {1, 0, 3}}; |
| 23 | + int[][] exp = { |
| 24 | + {1, 0, 3}, |
| 25 | + {1, 0, 3}, |
| 26 | + {0, 0, 0}}; |
| 27 | + |
| 28 | + solution1(matrix); |
| 29 | + |
| 30 | + for (int i = 0; i < exp.length; i++) { |
| 31 | + for (int j = 0; j < exp.length; j++) { |
| 32 | + assert exp[i][j] == matrix[i][j]; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + // Basic solution |
| 39 | + private void solution1(int[][] m) { |
| 40 | + List<Integer> r = new ArrayList<>(); |
| 41 | + List<Integer> c = new ArrayList<>(); |
| 42 | + |
| 43 | + for (int i = 0; i < m.length; i++) { |
| 44 | + for (int j = 0; j < m.length; j++) { |
| 45 | + if(0 == m[i][j]){ |
| 46 | + r.add(i); |
| 47 | + c.add(j); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + for (Integer i: r){ |
| 53 | + zerofied(m,i,null); |
| 54 | + } |
| 55 | + for (Integer i: c){ |
| 56 | + zerofied(m,null,i); |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + void zerofied(int[][] m, Integer r, Integer c){ |
| 63 | + for (int i = 0; i < m.length; i++) { |
| 64 | + for (int j = 0; j < m.length; j++) { |
| 65 | + if((r != null && r ==i ) || (c != null && c == j) ){ |
| 66 | + m[i][j] = 0; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments