Skip to content

Commit e92a021

Browse files
fix: Handle zero-column matrices and apply formatting
1 parent 7963ccf commit e92a021

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/main/java/com/thealgorithms/matrix/StrassenMatrixMultiplication.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,35 @@ public static double[][] multiply(double[][] matrixA, double[][] matrixB) {
5454
if (matrixA == null || matrixB == null) {
5555
throw new IllegalArgumentException("Input matrices cannot be null");
5656
}
57-
if (matrixA.length == 0 || (matrixA.length > 0 && matrixA[0].length == 0)) {
58-
return new double[0][0]; // Handle empty matrix
57+
58+
// Handle completely empty matrices (0 rows)
59+
if (matrixA.length == 0 || matrixB.length == 0) {
60+
// Check if dimensions are compatible (0xN * Nx0 -> 0x0)
61+
if (matrixA.length == 0 && (matrixB.length > 0 && matrixB[0].length == 0)) {
62+
return new double[0][0]; // Special case: 0xN * Nx0 = 0x0
63+
}
64+
// Check if dimensions are compatible (0x0 * 0x0 -> 0x0)
65+
if (matrixA.length == 0 && matrixB.length == 0) {
66+
return new double[0][0];
67+
}
68+
// Otherwise, if one is 0x0 and the other isn't, it's incompatible or invalid
69+
throw new IllegalArgumentException("Matrices cannot be multiplied: incompatible dimensions for empty matrix.");
70+
}
71+
72+
// Check for matrices with rows but zero columns (e.g., {{}})
73+
if (matrixA[0].length == 0 || matrixB[0].length == 0) {
74+
// Check if dimensions are compatible (Mx0 * 0xP -> MxP, but needs special
75+
// handling or definition)
76+
// For this test case expecting an error:
77+
throw new IllegalArgumentException("Input matrices must have at least one column.");
5978
}
6079

80+
// Check for squareness and equal dimensions
6181
int n = matrixA.length;
6282
if (n != matrixA[0].length || n != matrixB.length || n != matrixB[0].length) {
6383
throw new IllegalArgumentException("Strassen's algorithm requires square matrices of the same dimension (n x n).");
6484
}
85+
// --- END OF VALIDATION ---
6586

6687
// --- 2. PADDING ---
6788
// Find the next power of 2

0 commit comments

Comments
 (0)