// Function to add or subtract two matrices
public static int[,] add(int[,] arr, int[,] brr, int n, int sign) {
int[,] res = new int[n, n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res[i, j] = arr[i, j] + sign * brr[i, j];
}
}
return res;
}
// Strassen's matrix multiplication function
public static int[,] mult(int[,] arr, int[,] brr) {
int n = arr.GetLength(0);
int[,] res = new int[n, n];
// Base case
if (n == 1) {
res[0, 0] = arr[0, 0] * brr[0, 0];
return res;
}
int nwSz = n / 2; // New Size
int[,] a11 = new int[nwSz, nwSz];
int[,] a12 = new int[nwSz, nwSz];
int[,] a21 = new int[nwSz, nwSz];
int[,] a22 = new int[nwSz, nwSz];
int[,] b11 = new int[nwSz, nwSz];
int[,] b12 = new int[nwSz, nwSz];
int[,] b21 = new int[nwSz, nwSz];
int[,] b22 = new int[nwSz, nwSz];
// Splitting arr and brr into submatrices
for (int i = 0; i < nwSz; i++) {
for (int j = 0; j < nwSz; j++) {
a11[i, j] = arr[i, j];
a12[i, j] = arr[i, j + nwSz];
a21[i, j] = arr[i + nwSz, j];
a22[i, j] = arr[i + nwSz, j + nwSz];
b11[i, j] = brr[i, j];
b12[i, j] = brr[i, j + nwSz];
b21[i, j] = brr[i + nwSz, j];
b22[i, j] = brr[i + nwSz, j + nwSz];
}
}
// Strassen's seven multiplications
int[,] m1 = mult(add(a11, a22, nwSz, 1), add(b11, b22, nwSz, 1));
int[,] m2 = mult(add(a21, a22, nwSz, 1), b11);
int[,] m3 = mult(a11, add(b12, b22, nwSz, -1));
int[,] m4 = mult(a22, add(b21, b11, nwSz, -1));
int[,] m5 = mult(add(a11, a12, nwSz, 1), b22);
int[,] m6 = mult(add(a21, a11, nwSz, -1), add(b11, b12, nwSz, 1));
int[,] m7 = mult(add(a12, a22, nwSz, -1), add(b21, b22, nwSz, 1));
// Calculating result submatrices
int[,] c11 = add(add(m1, m4, nwSz, 1), add(m7, m5, nwSz, -1), nwSz);
int[,] c12 = add(m3, m5, nwSz, 1);
int[,] c21 = add(m2, m4, nwSz, 1);
int[,] c22 = add(add(m1, m3, nwSz, 1), add(m6, m2, nwSz, -1), nwSz);
// Copy results into result matrix
for (int i = 0; i < nwSz; i++) {
for (int j = 0; j < nwSz; j++) {
res[i, j] = c11[i, j];
res[i, j + nwSz] = c12[i, j];
res[i + nwSz, j] = c21[i, j];
res[i + nwSz, j + nwSz] = c22[i, j];
}
}
return res;
}
public static void Main(string[] args) {
int[,] arr = {{7, 8}, {2, 9}};
int[,] brr = {{14, 5}, {5, 18}};
int[,] res = mult(arr, brr);
foreach (var row in res) {
Console.WriteLine(string.Join(", ", row));
}
}