题解 | #矩阵幂#
矩阵幂
https://www.nowcoder.com/practice/31e539ab08f949a8bece2a7503e9319a
import java.util.Arrays; import java.util.Scanner; class Matrix { public static void mutl(int[][] matrix1, int[][] matrix2) { int len = matrix1.length; int[][] temp = new int[len][len]; int[][] temp2 = new int[len][len]; for (int i = 0; i < len; i++) { System.arraycopy(matrix1[i], 0, temp[i], 0, len); System.arraycopy(matrix2[i], 0, temp2[i], 0, len); } int g = 0; for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { int sum = 0; for (int k = 0; k < len; k++) { sum += temp[i][k] * temp2[k][j]; } matrix1[g / len][g % len] = sum; g++; } } } public static void add(int[][] m1, int [][]m2) { for (int i = 0; i < m1.length; i++) { for (int j = 0; j < m1[0].length; j++) { m1[i][j] += m2[i][j]; } } } public static int[][] getE(int n) { int[][] ans = new int[n][n]; for (int i = 0; i < n; i++) { ans[i][i] = 1; } return ans; } public static int[][] powK(int[][] matrix, int k) { int len = matrix.length; int [][] ans = getE(len); int [][] g = new int[len][len]; for (int i = 0; i < len; i++) { System.arraycopy(matrix[i], 0, g[i], 0, len); } while (k > 0) { if ((k & 1) == 1) { Matrix.mutl(ans, g); } Matrix.mutl(g, g); k >>= 1; } return ans; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int k = scanner.nextInt(); int[][] matrix = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = scanner.nextInt(); } } int[][] ans = Matrix.powK(matrix, k); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(ans[i][j] + " "); } System.out.println(); } } } }