Java 实现 n 阶行列式的求解

文章目录

题目

跳转链接

在这里插入图片描述

题解

  • 首先这里 运用 递归求解
  • 这位大佬题解写的非常不错 ,其他栏的蓝桥杯资料也不错 ! 😇

参考链接

  • 运用递归思路求其余子式

  • 这里运用 余子式 的拉普拉斯展开 求解行列式 😎

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();
	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值