Questions determinant calculation algorithm to improve
Resource constraints
Time limit: 1.0s memory limit: 256.0MB
Problem Description
// reportedly the subject of a lot of people have a lot of nonsense, the silly nonsense × not here.
Given an N × N matrix A, find | A |.
The input format
of the first line of a positive integer N.
Next N lines of N integers, the i-th row and j th number indicates A [i] [j].
Output format
line, the output of | A |.
Sample input
2
. 1 2
. 3. 4
sample output
-2
size of the data and agreed
0 <N≤6
-10≤A [I] [J] ≦ 10
PS: This question is difficult mathematical algorithm is not difficult
package com.company;
import java.util.Scanner;
public class 计算行列式 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] [] num = new int[n][n];
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
num[i][j]=sc.nextInt();
}
}
System.out.println(f(num,n));
}
public static int f(int num[][],int n){
if(n==1) return num[0][0];
if(n==2) return num[0][0]*num[1][1]-num[0][1]*num[1][0];
int ans = 0;
int tmp[][] =new int[8][8];
for(int i=0;i<n;++i)
{
for(int row=0; row<n-1; ++row)
{
for(int col=0; col<i; ++col)
tmp[row][col] = num[row+1][col];
for(int col=i; col<n-1;++col)
tmp[row][col] = num[row+1][col+1];
}
ans += num[0][i]*f(tmp,n-1)*(i%2==0?1:-1);
}
return ans;
}
}