-
Notifications
You must be signed in to change notification settings - Fork 46
/
_851.java
46 lines (38 loc) · 840 Bytes
/
_851.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
import java.util.Arrays;
/**
* LeetCode 851 - Loud and Rich
* <p>
* DAG
*/
public class _851 {
boolean[][] g;
int n;
int[] ans;
int[] quiet;
public int[] loudAndRich(int[][] richer, int[] quiet) {
this.quiet = quiet;
n = quiet.length;
g = new boolean[n][n];
for (int[] row : richer) {
g[row[0]][row[1]] = true;
}
ans = new int[n];
Arrays.fill(ans, -1);
for (int i = 0; i < n; i++) {
ans[i] = f(i);
}
return ans;
}
int f(int i) {
if (ans[i] != -1) {
return ans[i];
}
ans[i] = i;
for (int j = 0; j < n; j++) {
if (g[j][i] && quiet[f(j)] < quiet[ans[i]]) {
ans[i] = f(j);
}
}
return ans[i];
}
}