-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix_Determinant.cpp
More file actions
73 lines (52 loc) · 1.16 KB
/
Copy pathMatrix_Determinant.cpp
File metadata and controls
73 lines (52 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
using namespace std;
long long determinant(vector< vector<long long> > m)
{
if (m.size() == 1)
{
return m[0][0];
}
else if (m.size() == 2)
{
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
long long res = 0;
int sign = 1;
for (int i = 0; i < m.size(); i++)
{
vector<vector<long long>> sub;
for (int j = 1; j < m.size(); j++)
{
vector<long long> temp;
for (int k = 0; k < m.size(); k++)
{
if (k != i)
temp.push_back(m[j][k]);
}
sub.push_back(temp);
}
res += determinant(sub) * m[0][i] * sign;
sign *= -1;
}
return res;
}
/* BEST CODE
#include <iostream>
#include <vector>
using namespace std;
long long determinant(vector< vector<long long> > m) {
if (m.size() == 1) return m[0][0];
long long result = 0;
for (int i = 0; i < m.size(); i++) {
vector< vector<long long> > submatrix;
for (int j = 1; j < m.size(); j++) {
vector<long long> row;
for (int k = 0; k < m.size(); k++) if (k != i) row.push_back(m[j][k]);
submatrix.push_back(row);
}
result += determinant(submatrix) * (i % 2 == 0 ? m[0][i] : -m[0][i]);
}
return result;
}
*/