You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
The key idea is to find the connected components of the graph and analyze how many initial infected nodes are in each component. If a component contains exactly one initial node, removing it will prevent the infection of the entire component. We want to maximize the number of saved nodes, and in case of a tie, return the smallest index.
classSolution {
funminMalwareSpread(graph: Array<IntArray>, initial: IntArray): Int {
val n = graph.size
val par = IntArray(n) { it }
funfind(x: Int): Int = if (par[x] == x) x else { par[x] = find(par[x]); par[x] }
for (i in0 until n) for (j in0 until n) if (graph[i][j] ==1) par[find(i)] = find(j)
val cnt = mutableMapOf<Int, Int>()
val infected = mutableMapOf<Int, Int>()
for (i in0 until n) cnt[find(i)] = cnt.getOrDefault(find(i), 0) + 1for (u in initial) infected[find(u)] = infected.getOrDefault(find(u), 0) + 1 initial.sort()
var ans = -1var maxSaved = -1for (u in initial) {
val root = find(u)
if (infected[root] ==1&& cnt[root] > maxSaved) {
maxSaved = cnt[root]
ans = u
}
}
returnif (ans == -1) initial[0] else ans
}
}
classSolution:
defminMalwareSpread(self, graph: list[list[int]], initial: list[int]) -> int:
n = len(graph)
par = list(range(n))
deffind(x):
if par[x] != x:
par[x] = find(par[x])
return par[x]
for i in range(n):
for j in range(n):
if graph[i][j]:
par[find(i)] = find(j)
cnt = {}
infected = {}
for i in range(n):
root = find(i)
cnt[root] = cnt.get(root, 0) +1for u in initial:
root = find(u)
infected[root] = infected.get(root, 0) +1 ans =-1 maxSaved =-1for u in sorted(initial):
root = find(u)
if infected[root] ==1and cnt[root] > maxSaved:
maxSaved = cnt[root]
ans = u
return ans if ans !=-1else min(initial)