Ma trận vuông khả nghịch ⇔ định thức ≠ 0. Nghịch đảo M⁻¹ = adj(M) / det(M).
Giải thuật
Tính định thức đệ quy bằng mở rộng Laplace theo hàng đầu: - Tìm ma trận con (cofactor) bằng cách loại bỏ hàng 0, cột f - det = Σ (-1)ᶠ × mat[0][f] × det(cofactor) - Cơ sở: ma trận 1×1 trả về phần tử đó
Ví dụ minh họa
#include <iostream>
#define N 4
using namespace std;
void findCoFactor(int mat[N][N], int temp[N][N], int p, int q, int n) {
int i = 0, j = 0;
for (int row = 0; row < n; row++)
for (int col = 0; col < n; col++)
if (row != p && col != q) {
temp[i][j++] = mat[row][col];
if (j == n - 1) { j = 0; i++; }
}
}
int getDeterminant(int mat[N][N], int n) {
if (n == 1) return mat[0][0];
int temp[N][N];
int det = 0, sign = 1;
for (int f = 0; f < n; f++) {
findCoFactor(mat, temp, 0, f, n);
det += sign * mat[0][f] * getDeterminant(temp, n - 1);
sign = -sign;
}
return det;
}
bool isMatrixInvertible(int mat[N][N], int n) {
return getDeterminant(mat, n) != 0;
}
int main() {
int matrix[N][N] = {
{1, 0, 2, -1},
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}
};
cout << (isMatrixInvertible(matrix, N) ? "Ma tran kha nghich" : "Ma tran KHONG kha nghich");
}
Kết quả
Ma tran kha nghich