先看题目
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //N阶矩阵 int N = sc.nextInt(); //M次方 int M = sc.nextInt(); int[][] A= new int[N][N]; for (int i=0;i<N;i++){ for (int j=0;j<N;j++){ A[i][j] = sc.nextInt(); } } //0次幂 if(M == 0) { for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(i == j) { System.out.print(1 + " "); }else { System.out.print(0 + " "); } } System.out.println(); } }else if(M == 1){ for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { System.out.print(A[i][j] + " "); } System.out.println(); } }else { //当幂大于2时需要一个新的数组来配合计算 int[][] A1 = A; //i为幂 for (int i = 1; i < M; i++) { //暂时存储计算的值 int[][] result = new int[N][N]; for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { int count = 0; int temp = 0; while (count < N) { //第j行乘以第k列 temp += A[j][count] * A1[count][k]; count++; } result[j][k] = temp; } } //将结果给A数组 A = result; } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { System.out.print(A[i][j] + " "); } System.out.println(); } } } }