import java.util.Scanner; public class Main { public static int[][] multiply(int[][] matrix1,int[][] matrix2,int size){ int[][] result = new int[size][size]; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ result[i][j] = -1; } } for(int k = 0; k < size; k++){ for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ if(matrix1[i][k] < 0 || matrix2[k][j] < 0) continue; if(result[i][j] < 0 || result[i][j] > matrix1[i][k] + matrix2[k][j]){ result[i][j] = matrix1[i][k] + matrix2[k][j]; } } } } return result; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n =scan.nextInt(); int m = scan.nextInt(); int[][] number=new int[n][n]; int[][] result; int[][] ans; for(int i=0;i<n;i++){ for (int j = 0; j < n; j++){ number[i][j]=scan.nextInt(); if(number[i][j] == 0) number[i][j] = -1; } } result = ans = number; m--; while(m > 0){ if(m%2==1){ result = multiply(result,ans,n); } ans = multiply(ans,ans,n); m = m/2; } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ System.out.print(result[i][j] + ","); } System.out.println(); } } }
阿里笔试编程题 Floyd+快速幂
最新推荐文章于 2022-02-09 20:14:24 发布