forked from builder-of-web3/HackR_Java_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfriends_circle
More file actions
47 lines (43 loc) · 1.37 KB
/
friends_circle
File metadata and controls
47 lines (43 loc) · 1.37 KB
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
/*
* Complete the friendCircles function below.
*/
static int friendCircles(String[] friends) {
int len = friends.length;
char[][] matrix = new char[len][len];
for (int i = 0; i < len; i++) {
matrix[i] = friends[i].toCharArray();
}
int n = matrix.length;
if (n == 1) {
return 1;
}
boolean[] assigned = new boolean[n];
for (int i = 0; i < n; i++) {
assigned[i] = false;
}
int circles = 0;
for (int i = 0; i < n; i++) {
if (assigned[i]) continue;
assigned[i] = true;
for (int j = 0; j < matrix.length; j++) {
if (assigned[j]) continue;
if (i == j) continue;
if (matrix[i][j] == 'Y') {
assigned[j] = true;
updateInPlace(matrix, assigned, j);
}
}
circles++;
}
return circles;
}
private static void updateInPlace(char[][] matrix, boolean[] assigned, int i) {
for (int j = 0; j < matrix.length; j++) {
if (assigned[j]) continue;
if (i == j) continue;
if (matrix[i][j] == 'Y') {
assigned[j] = true;
updateInPlace(matrix, assigned, j);
}
}
}