首页 > 代码库 > [BASIC-17] 矩阵乘法

[BASIC-17] 矩阵乘法

基础练习 矩阵乘法  
时间限制:1.0s   内存限制:512.0MB
问题描述
  给定一个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 scanner = new Scanner(System.in);

		while (scanner.hasNext()) {
			int n = scanner.nextInt();
			int m = scanner.nextInt();

			int[][] init = new int[n][n];
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					init[i][j] = scanner.nextInt();
				}
			}

			int[][] result = new int[n][n];
			for (int i = 0; i < n; i++) {
				result[i][i] = 1;
			}

			powerOperation(result, init, m);
			printMatrix(result);
		}
	}

	private static void printMatrix(int[][] result) {
		int len = result.length;
		for (int i = 0; i < len; i++) {
			for (int j = 0; j < len; j++) {
				System.out.print(result[i][j]);
				System.out.print(j == len - 1 ? "\r\n" : " ");
			}
		}
	}

	private static void powerOperation(int[][] result, int[][] init, int m) {
		int len = init.length;
		for (int i = 0; i < m; i++) {		
			int[][] temp = new int[len][len];
			for (int j = 0; j < len; j++) {
				for (int j2 = 0; j2 < len; j2++) {
					for (int k = 0; k < len; k++) {
						temp[j][j2] += result[j][k] * init[k][j2];
					}
				}
			}

			for (int j = 0; j < len; j++) {
				for (int j2 = 0; j2 < len; j2++) {
					result[j][j2] = temp[j][j2];
				}
			}
		}
	}
}