-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathInfectionDistribution.java
More file actions
66 lines (56 loc) · 2.42 KB
/
InfectionDistribution.java
File metadata and controls
66 lines (56 loc) · 2.42 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package by.andd3dfx.common;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <pre>
* В королевстве есть несколько городов, соединенных дорогами. Города называются соседними, если между ними есть прямая
* дорога. Первоначально чума вспыхнула лишь в паре городов, однако каждую неделю соседние города чумного города также
* подвергались заражению и становились чумными.
* Задача определить через сколько недель все королевство будет заражено.
*
* Input:
* - cities_amount: n
* - roads: [[n_i, n_j], ...]
* - infected: [m_1, m_2, ...]
*
* Output:
* weeks_count
* </pre>
*
* @see <a href="https://youtu.be/Ei1uCCD_Iqg">Video solution (initial)</a>
* @see <a href="https://youtu.be/d9v9DS1YVtk">Video solution (final)</a>
*/
public class InfectionDistribution {
public static int weeksToInfectAllCities(int citiesAmount, int[][] roads, int[] infected) {
var adjMatrix = new boolean[citiesAmount][citiesAmount]; // adjacency matrix
Arrays.stream(roads).forEach(road -> {
adjMatrix[road[0]][road[1]] = true;
adjMatrix[road[1]][road[0]] = true;
});
var weeksAmount = 0;
var infectedCities = Arrays.stream(infected).boxed().collect(Collectors.toSet());
while (infectedCities.size() < citiesAmount) {
var newCities = determineNewInfectedCities(infectedCities, adjMatrix);
if (newCities.isEmpty()) {
return -1;
}
infectedCities.addAll(newCities);
weeksAmount++;
}
return weeksAmount;
}
private static Set<Integer> determineNewInfectedCities(Set<Integer> infectedCities, boolean[][] adjMatrix) {
var n = adjMatrix.length;
var newCities = new HashSet<Integer>();
for (var city : infectedCities) {
for (int i = 0; i < n; i++) {
if (adjMatrix[city][i] && !infectedCities.contains(i)) {
newCities.add(i);
}
}
}
return newCities;
}
}