Tuesday, September 3, 2013

1.7----- set entire row and column as zeros if element is 0

Q:

Write an algorithm such that if an element in an MxN matrix is 0, its entire row
and column are set to 0

A:
using two index array to remember which row(column ) would be set to zeros.





public class code1_1 {
public class code1_1 {

 public static void main(String[] args) {

  // String str = " 234o;908aslfjz";
  int M = 8;
  int N = 7;
  int[][] arr = new int[M][N];
  initializeArray(arr);
  // print out the array.
  for (int i = 0; i < M; i++) {
   for (int j = 0; j < N; j++) {
    System.out.print(arr[i][j] + "\t");
   }
   System.out.println();
  }

  checkAndSetZero(arr);
  System.out.println();
  System.out.println();
  // print out the array.
  for (int i = 0; i < M; i++) {
   for (int j = 0; j < N; j++) {
    System.out.print(arr[i][j] + "\t");
   }
   System.out.println();
  }
 }

 private static void checkAndSetZero(int[][] array) {
  int row = array.length;
  int col = array[0].length;
  int[] rowIndex = new int[row];
  int[] colIndex = new int[col];
  // check zero, and set indexes
  for (int i = 0; i < row; i++) {
   for (int j = 0; j < col; j++) {
    if (array[i][j] == 0) {
     rowIndex[i] = 1;
     colIndex[j] = 1;
    }
   }
  }
  // set the rows into 0s, if rowIndex is zeros
  for (int i = 0; i < row; i++) {
   if (rowIndex[i] != 0) {
    // change the whole row as zero
    for (int j = 0; j < col; j++) {
     array[i][j] = 0;
    }
   }
  }
  // set the col into 0s, if colIndex is zeros
  for (int j = 0; j < col; j++) {
   if (colIndex[j] != 0) {
    // change the whole row as zero
    for (int i = 0; i < row; i++) {
     array[i][j] = 0;
    }
   }
  }
 }

 private static void initializeArray(int[][] arr) {
  // TODO Auto-generated method stub
  int row = arr.length;
  int col = arr[0].length;
  for (int i = 0; i < row; i++) {
   for (int j = 0; j < col; j++) {
    arr[i][j] = (int) (Math.random() * 50);
   }
  }
 }

}
Mistakes:

 Learned:
Use two index array

No comments:

Post a Comment