/**
* LCP 07. 传递信息
*
* 线性代数,离散数学,图论基础知识
* 矩阵相乘
* 快速幂
*
*/
public class SolutionLCP07 {
public int numWays(int n, int[][] relation, int k) {
// 初始化单位矩阵
int[][] identityMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
identityMatrix[i][i] = 1;
}
// 求邻接矩阵
int[][] adjacencyMatrix = new int[n][n];
for (int[] array : relation) {
adjacencyMatrix[array[0]][array[1]] = 1;
}
// 作k次幂
while(k!=0){
if((k&1)==1) {
identityMatrix = multiply(identityMatrix, adjacencyMatrix);
}
k>>=1;
adjacencyMatrix = multiply(adjacencyMatrix,adjacencyMatrix);
}
return identityMatrix[0][n-1];
}
// 快速幂模板
public static int[][] multiply(int[][] A,int[][] B){
int res[][] = new int[A.length][B.length];
for(int i = 0 ; i < res.length ;i++){
for(int j = 0 ; j< res[i].length ;j++){
for(int k = 0 ; k < A[0].length ;k++){
res[i][j] += A[i][k]*B[k][j];
}
}
}
return res;
}
public static void main(String[] args) {
SolutionLCP07 solutionJZ38 = new SolutionLCP07();
int[][] temp = new int[][]{{0,2},{2,1},{3,4},{2,3},{1,4},{2,0},{0,4}};
solutionJZ38.numWays(5, temp, 3);
}
}
LeetCode -- LCP 07. 传递信息
最新推荐文章于 2021-08-22 21:15:23 发布