 user2017502 - 4 years ago 135
Java Question

# Java - Zero out the rows/columns of 2d array if it contains a target number

Given a mxn matrix that looks like this:

1034

1234

3560

Need to output something like this:

0000

1030

0000

*Target number is 0.

Here's my solution, but I think it's not very efficient (both space and running time which I believe is O(m^2 * n)) and was wondering if there are simpler and more efficient ways to do this. If yes, what is it?

``````int[][] m = { { 1, 0, 3, 4 }, { 1, 2, 3, 4 }, { 3, 5, 6, 0 } };
m = zero(m, 0);

public static int[][] zero(int[][] m, int num) {

int rows = m.length;
int columns = m.length;
int [][] myInt = new int[rows][];
for(int i = 0; i < rows; i++){
myInt[i] = m[i].clone();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (myInt[i][j] == num) {
m[i] = new int[columns];
for(int k = 0; k < rows; k++){
m[k][j] = 0;
}
break;
}
}
}
return m;
}
``````

Basically I clone the input matrix first, then iterate through each row and check if the row contains my target number. If yes, then I set the entire row in the original matrix to zero. Then I do another loop to set the column which contains the target number to zero. I cloned the matrix in the beginning so the checking is always against the cloned reference matrix instead of the modified one at each iteration. Joop Eggen

I propose using BitSet for row/column indices.

``````public static void zero(int[][] m, int num) {

int rows = m.length;
int columns = m.length;
BitSet rowsToClear = new BitSet(rows);
BitSet columnsToClear = new BitSet(columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (m[i][j] == num) {
rowsToClear.set(i);
columnsToClear.set(j);
}
}
}
for (int i = rowsToClear.nextSetBit(0); i >= 0;
i = rowsToClear.nextSetBit(i + 1)) {
Arrays.fill(m[i], 0);
}
for (int j = columnsToClear.nextSetBit(0); j >= 0;
j = columnsToClear.nextSetBit(j + 1)) {
for (int i = 0; i < rows; ++i) {
m[i][j] = 0;
}
}
//return m;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download