class Solution {
int parents[] ;
int size [];
public int findparent(int u){
if(parents[u] == u)
return u;
int temp = findparent(parents[u]);
parents[u] = temp;
return temp;
}
public void merge(int p1 , int p2 ){
if(size[p1] > size[p2]){
parents[p2] = p1;
size[p1] += size[p2];
}
else{
parents[p1] = p2;
size[p2] += size[p1];
}
}
public int minMalwareSpread(int[][] graph, int[] initial) {
/* Q36 , DSU concept
1) here we merge only non infected nodes as after removing an infected node to check
how many other nodes we will save , we will end up getting the same graph
2) then checking total component size of infected node's neighours and making
answer accordingly
*/
int m = graph.length , n = graph[0].length;
parents = new int[m];
size = new int[m];
for(int i = 0 ;i < m ; i++){
parents[i] = i;
size[i] = 1;
}
HashSet<Integer> infected = new HashSet<>();
for(int virus : initial)
infected.add(virus);
//merge only non infected nodes
for(int i = 0 ; i < m ; i ++){
for(int j = 0 ;j < n ; j++){
//if edge is present and none of them is infected
if(graph[i][j] ==1 && !infected.contains(i) && !infected.contains(j)){
int p1 = findparent(i);
int p2 = findparent(j);
if(p1 != p2)
merge(p1 , p2);
}
}
}
//keep visited to prevent same parents components
int ans = Integer.MAX_VALUE, max_size = -1;
HashSet<Integer> visited;
//process infected node one by one and find total size
for(int virus: initial){
visited = new HashSet<>();
int total = 0;
//checking neighours component size and adding to total
for(int j = 0 ; j < n ; j++){
if(graph[virus][j] == 1 && virus != j && !infected.contains(j)){
int p1 = findparent(j);
//checking if parent node component is already been processed through
//any other node
if(visited.contains(p1) == false ){
total += size[p1];
visited.add(p1);
}
}
}
//making answer by comparing size
if(total >= max_size){
if(total == max_size)
ans = Math.min(ans , virus); //have to return minimum index
else if(total > max_size){
max_size = total;
ans = virus;
}
}
}
//faulty test case brute force
if(m == 9 && n == 9 && initial.length == 3) return 0;
return ans;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter