题目
题解
- 首先这里 运用 递归求解
- 这位大佬题解写的非常不错 ,其他栏的蓝桥杯资料也不错 ! 😇
-
运用递归思路求其余子式
-
这里运用 余子式 的拉普拉斯展开 求解行列式 😎
A11A12…A1n
A21A22…A2n
…
An1An2…Ann
所以当n == 2时就是递归出口了, n > 2 递归计算。
代码
package BaseFunction;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* @author LZH.create
* 计算 n 阶行列 的值
*/
public class determinant_demo {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static int Int(String s){return Integer.parseInt(s);}
// 注意 为 n 阶行列式 --> n x n
/**
*
* @param A 被复制 原数组
* @param A1 新数组
* @param i 列号 用于确定系数 与被排除 的列
* @param len 矩阵的 边
* @throws IOException
*/
public static void copy(int[][]A, int[][] A1, int i, int len) throws IOException{
for(int x = 1; x < len; x++)
for(int y = 0, j = 0; j < len; j++)
if(j != i) {
A1[x-1][y++] = A[x][j];
}
}
// 求余子式 算法 (用于三项及其 以上)
public static int F(int[][] A, int len)throws Exception{
int res = 0;
if(len == 1)return A[0][0];
if(len == 2){
return A[0][0]*A[1][1] - A[0][1]*A[1][0]; // 递归出口
}
else{
int A1[][] = new int[10][10];
for(int i = 0; i < len; i++){
copy(A, A1, i, len);// 得到余子式
res += Math.pow(-1, i) * A[0][i] * F(A1, len-1); //递归式
}
}
return res;
}
public static void main(String[] args) throws Exception{
int n;
n = Integer.parseInt(in.readLine());
int arr[][] = new int[10][10];
for(int i = 0; i < n; i++){
String[] s = in.readLine().split(" ");
for(int j = 0; j < n; j++){
arr[i][j] = Int(s[j]);
}
}
out.write(F(arr, n) + "\n");
out.flush();
}
}