蓝桥杯(基础练习)——矩阵乘法

问题描述
  给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
  例如:
  A =
  1 2
  3 4
  A的2次幂
  7 10
  15 22
输入格式
  第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数
  接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出格式
  输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2
1 2
3 4
样例输出
7 10
15 22

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		// 存数
		int[][] a = new int[n][n];
		int[][] result = new int[n][n];// 结果
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				a[i][j] = sc.nextInt();
			}
		}

		/*// 测试,输出
		System.out.println("输入的矩阵为:");
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(a[i][j]+" ");
			}
			System.out.println();
		}*/

		//递归求m次幂
		result=a.clone();
		if(m==0){
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					if(j==i){
						result[i][j]=1;
					}else{
						result[i][j]=0;
					}
				}
			}
		}else if(m==1){
			result = a;
		}else{
			while(m>1){
			result = Main.getProduct(a, result, n);
				m--;
			}
		
		}
		Main.showResult(result);
		
	}
	// 求两个n阶矩阵的积
	public static int[][] getProduct(int[][] a, int[][] b, int n) {
		
		int[][] result = new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int y = 0; y < n; y++) {
					result[i][j] += a[i][y] * b[y][j];
				}
			}
		}
		return result;
	}

	//显示结果
	public static void showResult(int[][] result){
	/*	System.out.println("输出结果:");*/
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j <result.length; j++) {
				System.out.print(result[i][j] + " ");
			}
			System.out.println();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39487875/article/details/86645515