1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-22 16:43:46 +01:00
CodeWars/4kyu/matrix_determinant/solution.cpp

45 lines
995 B
C++
Raw Normal View History

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
vector<vector<long long>> transform(vector<vector<long long>> m, int row,
int col) {
vector<vector<long long>> result;
for (int i = 0; i < m.size(); i++) {
if (i == row)
continue;
vector<long long> actual_row;
for (int j = 0; j < m[i].size(); j++) {
if (j == col)
continue;
actual_row.push_back(m[i][j]);
}
result.push_back(actual_row);
}
return result;
}
long long determinant(vector<vector<long long>> m) {
switch (m.size()) {
case 1:
return m[0][0];
break;
case 2:
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
break;
}
long long result = 0;
for (int i = 0; i < m.size(); i++) {
auto l_m = transform(m, i, 0);
result += pow(-1, i + 2) * m[i][0] * determinant(l_m);
}
return result;
}