g0901_1000.s0924_minimize_malware_spread.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0901_1000.s0924_minimize_malware_spread;
// #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find
import java.util.HashMap;
import java.util.HashSet;
public class Solution {
private int[][] par;
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
par = new int[n][2];
for (int i = 0; i < par.length; i++) {
par[i][0] = i;
par[i][1] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (graph[i][j] == 1) {
int li = find(i);
int lj = find(j);
if (li != lj) {
par[li][0] = lj;
par[lj][1] += par[li][1];
}
}
}
}
HashMap> map = new HashMap<>();
for (int val : initial) {
int lv = find(val);
if (!map.containsKey(lv)) {
map.put(lv, new HashSet<>());
}
map.get(lv).add(val);
}
int ans = -1;
int max = Integer.MIN_VALUE;
for (int val : initial) {
int lv = find(val);
if (map.get(lv).size() == 1) {
if (par[lv][1] > max) {
max = par[lv][1];
ans = val;
} else if (par[lv][1] == max && val < ans) {
ans = val;
}
} else {
if (max < 0) {
max = 0;
ans = val;
} else if (max == 0 && val < ans) {
ans = val;
}
}
}
return ans;
}
private int find(int x) {
if (par[x][0] == x) {
return x;
}
return find(par[x][0]);
}
}