Wednesday, August 7, 2013

Coding Exercises Day 5 (Problem #7)

Problem:
Write an algorithm such that if an element in an MxN matrix is 0, it's entire row and column are set to 0.
void fillWithZeros(int[][] matrix) {

  int m = matrix[0].length; // num rows
  int n = matrix.length; // num columns

  Set rows = new HashSet(m);
  Set columns = new HashSet(n);
  
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      if (0 == matrix[i][j]) {
        rows.add(i);
        columns.add(j);
      }
    }
  }

  for (int i : rows) {
    for (int j = 0; j < n; j++) {
      matrix[i][j] = 0;
    }
  }

  for (int j : columns) {
    for (int i = 0; j < m; i++) {
      matrix[i][j] = 0;
    }  
  }
}

No comments:

Post a Comment