解题思路:
主要是考矩阵怎么相乘吧,百度一下矩阵乘法就可以
注意事项:
注意矩阵的零次幂就行,我第一次提交的时候就是因为没有考虑到矩阵的零次幂答案错误了
参考代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[][] num = new int[n][n]; int[][] result = new int[n][n]; for (int i = 0; i < num.length; i++) { for (int j = 0; j < num[i].length; j++) { num[i][j] = scanner.nextInt(); result[i][j] = num[i][j]; } } if (m == 0) { for (int i = 0; i < num.length; i++) { for (int j = 0; j < num[i].length; j++) { if (i == j) { System.out.print(1 + " "); } else { System.out.print(0 + " "); } } System.out.println(); } } else { for (int i = 2; i <= m; i++) { result = matrixMul(num, result); } for (int[] is : result) { for (int is2 : is) { System.out.print(is2 + " "); } System.out.println(); } } } public static int[][] matrixMul(int[][] matrix1, int[][] matrix2) { int[][] result = new int[matrix1.length][matrix1.length]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[i].length; j++) { for (int j2 = 0; j2 < result.length; j2++) { result[i][j] = result[i][j] + matrix1[i][j2]*matrix2[j2][j]; } } } return result; } }
0.0分
0 人评分