-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeterminantOfMatrix.java
55 lines (51 loc) · 1.6 KB
/
DeterminantOfMatrix.java
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
package com.thealgorithms.maths;
import java.util.*;
/*
* @author Ojasva Jain
* Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant
*/
public class DeterminantOfMatrix {
// Determinant calculator
//@return determinant of the input matrix
static int determinant(int a[][], int n) {
int det = 0, sign = 1, p = 0, q = 0;
if (n == 1) {
det = a[0][0];
} else {
int b[][] = new int[n - 1][n - 1];
for (int x = 0; x < n; x++) {
p = 0;
q = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != x) {
b[p][q++] = a[i][j];
if (q % (n - 1) == 0) {
p++;
q = 0;
}
}
}
}
det = det + a[0][x] * determinant(b, n - 1) * sign;
sign = -sign;
}
}
return det;
}
//Driver Method
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Input Matrix
System.out.println("Enter matrix size (Square matrix only)");
int n = in.nextInt();
System.out.println("Enter matrix");
int a[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println(determinant(a, n));
}
}