-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path05-NumberOfPathsOfFixedLength.java
107 lines (89 loc) · 2.78 KB
/
05-NumberOfPathsOfFixedLength.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package graphs;
import java.util.Arrays;
public class NumberOfPathsOfFixedLength {
public static class PathsIndex {
private final int k;
private int[][] matrix;
/**
* Create an index over the given graph that can answer
* queries about the number of paths of some fixed length k.
*
* Build time: O(V^3)
* Query time: O(1)
*
* @param k the length of the paths.
*/
public PathsIndex(Graph g, int k) {
this.k = k;
matrix = g.getAdjacencyMatrix();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[i][j] > 0) {
matrix[i][j] = 1;
}
}
}
matrix = powMatrix(matrix, k);
}
/**
* Retrurns the number of paths starting at from and ending at to with length k.
*
* @param from starting vertex
* @param to ending vertex
* @return one integer - the number of paths.
*/
public int paths(int from, int to) {
return matrix[from][to];
}
/**
* @return the length of the paths.
*/
public int pathLength() {
return k;
}
private int[][] powMatrix(int[][] mat, int degree) {
if (degree == 0) {
return identityMatrix(mat.length);
}
if (degree == 1) {
return mat;
}
int[][] res = powMatrix(mat, degree / 2);
res = multiplyMatrix(res, res);
if (degree % 2 == 0) {
return res;
}
return multiplyMatrix(res, mat);
}
private int[][] identityMatrix(int size) {
int[][] res = new int[size][size];
for (int i = 0; i < size; i++) {
res[i][i] = 1;
}
return res;
}
private int[][] multiplyMatrix(int[][] a, int[][] b) {
int[][] res = new int[a.length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
for (int p = 0; p < a.length; p++) {
res[i][j] += a[i][p] * b[p][j];
}
}
}
return res;
}
}
/**
* Create an index over the given graph that can answer
* queries about the number of paths of some fixed length k.
*
* Build time: O(V^3)
* Query time: O(1)
*
* @param k the length of the paths.
*/
public static PathsIndex createIndex(Graph graph, int k) {
return new PathsIndex(graph, k);
}
}