Java实现 蓝桥杯 算法提高 计算行列式

试题 算法提高 计算行列式

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  //据说很多人的题目会有一大堆废话,本傻×就不在这里废话了。
  给定一个N×N的矩阵A,求|A|。
输入格式
  第一行一个正整数N。
  接下来N行,每行N个整数,第i行第j个数字表示A[i][j]。
输出格式
  一行,输出|A|。
样例输入
2
1 2
3 4
样例输出
-2
数据规模和约定
  0<N≤6
  -10≤A[i][j]≤10

PS:这个题还是数学有难度,算法并不难

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

发布了1103 篇原创文章 · 获赞 6923 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104258533