Friday, February 25, 2011

Given M-by-N matrix all the elements of the j-th row and k-th column to 0 if matrix[k][j] is 1

Suppose you have a (i.e. M rows and N columns), whose entries are all integers. Set all the elements of the j-th row and k-th column to 0 if matrix[k][j] is 1.

For instance, if the matrix is:

1 1 2 15
3 0 1 7
0 3 9 10
2 4 6 8

then, the result should be:

0 0 0 0
0 0 0 0
0 0 0 10
0 0 0 8



class matrix_ones
{


public static void setOnes(int[][] matrix)
{
int[] row = new int[matrix.length];
int[] column = new int[matrix[0].length];
// Store the row and column index with value 0
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length;j++)
{

if (matrix[i][j] == 1)
{
row[i] = 1;
column[j] = 1;
}

}

}

// Set arr[i][j] to 0 if either row i or column j has a 0
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if ((row[i] == 1 || column[j] == 1)) {
matrix[i][j] = 0;
}
}
}
}


public static void main(String a[])
{
int ar[][]=new int[][]{
{1, 1 ,2 ,15},
{3 ,0 ,1 ,7},
{0, 3, 9, 10},
{2 ,4 ,6 ,8}

};


setOnes(ar);

for (int i = 0; i <4; i++)
{
for (int j = 0; j < 4;j++)
{

System.out.println(ar[i][j]);

}
System.out.println();


}

}


}

1 comment :

suyash said...

I guess here o/p should be
0 0 0 0
0 0 0 0
0 0 0 0
0 0 6 8

because we are saying set all elements of jth row and kth columnt to 0....

here possible values of j are 0,1,2
and possible values of k are 0,1

considering as per given condition matrix[k][j]=1