java算法递归——求行列式的值

递归算法学习1

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class DiGui {
    
    

	
	public static int F(int [][]A,int len) {
    
                        //获取行列式函数
		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);                               //调用copy获得余子式
				
				res += Math.pow(-1, i)*A[0][i]*F(A1,len-1);     //递归式子
				
			}
			return res;                                         //返回最终值
		}
	}

关键点:代数余子式的计算函数


	public static void copy(int A[][],int A1[][],int i,int len) {
    
       
		for(int x=1;x<len;x++)                       //第一行的都不要
			for(int y=0,j=0;j<len;j++) {
    
    
				if(j!=i) {
    
                               //第i列的都不要
					A1[x-1][y++] = A[x][j];          //余子式赋值
				}
				
			}
	}

主函数


	public static void main(String[] args) throws Exception {
    
    
		Scanner s = new Scanner(System.in);
		int n,res;
		n = s.nextInt();
		
		int arr[][] = new int[n][n];
		for(int i=0;i<n;i++) {
    
    
			for(int j=0;j<n;j++) {
    
    
				arr[i][j]=s.nextInt();
			}
		}
		for(int i=0;i<n;i++) {
    
    
		
			for(int j=0;j<n;j++) {
    
    
				System.out.print(arr[i][j] + " ");
			}
			System.out.println("\n");
		}


		res = F(arr,n);
		System.out.println(res);
		
	}
}

2020.11.2 23:22

猜你喜欢

转载自blog.csdn.net/weixin_44919936/article/details/109459996