珠海做網(wǎng)站專業(yè)公司seo是搜索引擎優(yōu)化
描述
給定一個n*n的矩陣,求該矩陣的k次冪,即P^k。
輸入描述:
第一行:兩個整數(shù)n(2<=n<=10)、k(1<=k<=5),兩個數(shù)字之間用一個空格隔開,含義如上所示。 接下來有n行,每行n個正整數(shù),其中,第i行第j個整數(shù)表示矩陣中第i行第j列的矩陣元素Pij且(0<=Pij<=10)。另外,數(shù)據(jù)保證最后結(jié)果不會超過10^8。
輸出描述:
對于每組測試數(shù)據(jù),輸出其結(jié)果。格式為: n行n列個整數(shù),每行數(shù)之間用空格隔開,注意,每行最后一個數(shù)后面不應(yīng)該有多余的空格。
示例1
輸入:
2 2 9 8 9 3 3 3 4 8 4 9 3 0 3 5 7 5 2 4 0 3 0 1 0 0 5 8 5 8 9 8 5 3 9 6 1 7 8 7 2 5 7 3
輸出:
153 96 108 81 1216 1248 708 1089 927 504 1161 1151 739 47 29 41 22 16 147 103 73 116 94 162 108 153 168 126 163 67 112 158 122 152 93 93 111 97
代碼如下:
import java.util.Scanner;/** 矩陣冪*/
public class MatrixPower {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while(scanner.hasNext()) {int n = scanner.nextInt();int k = scanner.nextInt();int[][] arr = new int[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {arr[i][j] = scanner.nextInt();}}int[][] a = arr;for (int t = 0; t < k-1; t++) {//temp矩陣為arr矩陣的t+2次方int[][] temp = new int[n][n];//矩陣乘法的得到的結(jié)果保存到temp中for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {for (int k1 = 0; k1 < n; k1++) {temp[i][j] += a[i][k1] * arr[k1][j];}}}a = temp;}for(int i = 0;i < n; i++) {for(int j = 0;j < n; j++) {System.out.print(a[i][j]+" ");}System.out.println();}}}}