Minimize Malware Spread
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1Last updated
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1Last updated
class Solution {
int[] f;
int[] size;
public int minMalwareSpread(int[][] graph, int[] initial) {
if(graph == null || graph.length== 0){
return 0;
}
int n =graph.length;
f = new int[n];
size = new int[n];
//忘了初始化,错半死
for (int i = 0; i < n; i++) {
f[i] = i;
size[i] = 1;
}
for(int i = 0; i < n; i ++){
for(int j = i+1; j < n; j++){
if(graph[i][j] == 1){
union(i,j);
}
}
}
Arrays.sort(initial);
int[] malware =new int[n];
for (int i : initial){
malware[find(i)] ++;
}
int res= 0, x = initial[0];
for(int i : initial){
int ri = find(i);
if(malware[ri] == 1){
if (res < size[ri]){
res = size[ri];
x = i;
}
}
}
return x;
}
public int find(int x){
if(f[x] == x){
return x;
}
return f[x] = find(f[x]);
}
public void union(int x, int y){
int rx = find(x);
int ry = find(y);
if(rx != ry){
f[rx] = ry;
size[ry] += size[rx];
}
}
}class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
if not graph or not graph[0]:
return 0
d = [-1,0,1,0,-1]
n = len(graph)
ts = set()
def dfs(i,s):
s.add(i)
for j in range(n):
if j not in s and graph[i][j] == 1:
dfs(j,s)
initial = set(initial)
rank = collections.defaultdict(list)
save,res = 0,min(initial)
for i in initial:
if i not in ts:
s= set()
dfs(i,s)
if s&initial == {i}:
if save < len(s) or save == len(s) and res > i:
res = i
save = len(s)
ts |= s
return res
class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
if not graph or not graph[0]:
return 0
d = [-1,0,1,0,-1]
n = len(graph)
ts = set()
def dfs(i,s):
s.add(i)
for j in range(n):
if j not in s and graph[i][j] == 1:
dfs(j,s)
initial = set(initial)
rank = collections.defaultdict(list)
save,res = 0,min(initial)
for i in initial:
if i not in ts:
s= set()
dfs(i,s)
if s&initial == {i}:
if save < len(s) or save == len(s) and res > i:
res = i
save = len(s)
ts |= s
return res