924. 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
int findRoot(vector<int>& roots, int i) {
return roots[i] == i ? i : roots[i] = findRoot(roots, roots[i]);
}
void quickUnion(vector<int>& roots, vector<int>& size, int i, int j) {
int p = findRoot(roots, i), q = findRoot(roots, j);
if (p == q) return;
if (size[p] < size[q]) {
roots[p] = q;
size[q] += size[p];
} else {
roots[q] = p;
size[p] += size[q];
}
}
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { // time: O(n^2 * log*(n)); space: O(n)
int n = graph.size();
vector<int> roots(n, 0), size(n, 1), malCnt(n, 0);
// Initialize roots array
for (int i = 0; i < n; ++i) roots[i] = i;
// Union nodes based on graph
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (graph[i][j]) quickUnion(roots, size, i, j);
}
}
// Count malware
for (int init : initial) {
++malCnt[findRoot(roots, init)];
}
// vector<int> res = {1, 0};
// for (int i : initial)
// res = min(res, {(malCnt[findRoot(roots, i)] == 1 ) * (-size[findRoot(roots, i)]), i});
// return res[1];
int res = -1, maxSize = 0;
sort(initial.begin(), initial.end());
for (int i : initial) {
int r_i = findRoot(roots, i);
if (malCnt[r_i] == 1 && size[r_i] > maxSize) {
maxSize = size[r_i];
res = i;
}
}
if (maxSize != 0) return res;
else return initial[0];
}