Problem
If an element in an MxN matrix is 0, set its entire row and column to 0
Solution
public class ZeroRowAndCol{
public static void main(String...strings){
int[][] matrix = new int[5][4];
ZeroRowAndCol.Initialize(matrix);
ZeroRowAndCol.Print(matrix);
ZeroRowAndCol.Zero(matrix);
ZeroRowAndCol.Print(matrix);
}
private static void Initialize(int[][] matrix){
for(int j = 0; j < matrix.length; ++j){
for(int i = 0; i < matrix[0].length; ++i){
matrix[j][i] = j * matrix.length + i - matrix.length * matrix[0].length / 2;
}
}
}
private static void Print(int[][] matrix){
for(int j = 0; j < matrix.length; ++j){
for(int i = 0; i < matrix[0].length; ++i){
System.out.print(matrix[j][i] + ",");
}
System.out.println("\n");
}
}
private static void Zero(int[][] matrix){
int[] row = new int[matrix.length];
int[] col = new int[matrix[0].length];
for(int i = 0; i < row.length; ++i){
row[i] = 1;
}
for(int i = 0; i < col.length; ++i){
col[i] = 1;
}
for(int j = 0; j < row.length; ++j){
for(int i = 0; i < col.length; ++i){
if(matrix[j][i] == 0){
row[j] = 0;
col[i] = 0;
}
}
}
for(int j = 0; j < row.length; ++j){
for(int i = 0; i < col.length; ++i){
matrix[j][i] *= row[j] * col[i];
}
}
}
}
Output
-10,-9,-8,-7,
-5,-4,-3,-2,
0,1,2,3,
5,6,7,8,
10,11,12,13,
0,-9,-8,-7,
0,-4,-3,-2,
0,0,0,0,
0,6,7,8,
0,11,12,13,