Skip to content

Commit

Permalink
Update 924.Minimize-Malware-Spread.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Nov 6, 2022
1 parent 044c016 commit bb8b9f8
Showing 1 changed file with 69 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1 +1,69 @@

class Solution {
unordered_map<int,int>Root;
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial)
{
int N = graph.size();
for (int i=0; i<N; i++)
Root[i] = i;
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
{
if (i==j) continue;
if (graph[i][j]==0) continue;
if (findRoot(i)!=findRoot(j))
Union(i,j);
}

unordered_map<int,vector<int>>Children;
for (int i=0; i<N; i++)
{
Root[i] = findRoot(i);
Children[Root[i]].push_back(i);
}

set<int>Set(initial.begin(),initial.end());

int MaxGroup = 0;
int result;
for (auto a:Children)
{
int count = 0;
int candidate;
for (auto b:a.second)
{
if (Set.find(b)!=Set.end())
{
count++;
candidate = b;
}
if (count>1) break;
}
if (count==1 && (a.second.size()>MaxGroup || a.second.size()==MaxGroup && candidate<result))
{
MaxGroup = a.second.size();
result = candidate;
}
}

if (MaxGroup!=0) return result;
else return *Set.begin();
}

int findRoot(int x)
{
if (Root[x]!=x)
Root[x] = findRoot(Root[x]);
return Root[x];
}

void Union(int x, int y)
{
x = Root[x];
y = Root[y];
if (x<y)
Root[y] = x;
else
Root[x] = y;
}
};

0 comments on commit bb8b9f8

Please sign in to comment.