public class Solution {
public int[][] multiply(int[][] A, int[][] B) {
int[][] rst = new int[A.length][B[0].length];
boolean[] rowA = new boolean[A.length];
boolean[] colB = new boolean[B[0].length];
// find non-zero element
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
if (A[i][j] != 0) {
rowA[i] = true;
}
}
}
for (int i = 0; i < B[0].length; i++) {
for (int j = 0; j < B.length; j++) {
if (B[j][i] != 0) {
colB[i] = true;
}
}
}
for (int i = 0; i < A.length; i++) {
for (int k = 0; k < B[0].length; k++) {
if (!rowA[i] || !colB[k]) {
rst[i][k] = 0;
continue;
}
int sum = 0;
for (int j = 0; j < A[0].length; j++) {
sum += A[i][j] * B[j][k];
}
rst[i][k] = sum;
}
}
return rst;
}
}